1billion 0.1.0 → 0.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 78c6eeb54b13842149735e3952342d1df6cc842d839ef2613ab514f88614e154
4
- data.tar.gz: c36f261aeba5d655864b46799822cdda662460cc7ba3f282409b1bbc91cbfc3a
3
+ metadata.gz: 9824691556972994a4eb89fd47e7947230fb10dcf8f10cf64321090cd1929f6c
4
+ data.tar.gz: 67d43a87990d424eb9eb34ed1b0186d5ab15226600e26d85aea08ef868e84d27
5
5
  SHA512:
6
- metadata.gz: e4645bfe43ecd62f36aa1b2ac00f4c3d6ad15c3f076a9ec9deb273a4ed170eb1e485d6cf6293722e74af25dd1bff7da97f46df7258f9f8656adeb3ac5f1ee0c1
7
- data.tar.gz: 3aec8ade1e1dc23ae0f5b48fd532c3d81faffad982ad88e19f2b025febdeb92ba1298a834833d7eccab8529a6d68635806e44deb840df7687418bbc2ea8fbfea
6
+ metadata.gz: 01fb1f357ffc560d6666915724ac0f439ec3fd50eeaf7fdede5ef831a8f2366293e1caa4256075f5b740d8af99b68c1232dd155ad561bd81a279b436a9c09342
7
+ data.tar.gz: 11d08d36f95c1cc28c51a2b47601fd3333052a4412f920e3ddcf14cd98d55f17f531c36e1d5d372a6e817ca8f21a22fd866a4ce5cd55ba5e99d7d2b4920a8181
data/README.md CHANGED
@@ -42,17 +42,21 @@ bundle add 1billion
42
42
  Ruby 3.1 or newer. The gem is named `1billion`; its code is under `OneBillion`, because a Ruby constant can
43
43
  not start with a digit.
44
44
 
45
- Make an API key in the [console](https://1billion.clowk.in), and verify the domain that you send from.
45
+ Make an API key in the [console](https://1billion.clowk.in), and verify the domain that you send from. Put the
46
+ key in the environment:
47
+
48
+ ```bash
49
+ export ONEBILLION_API_KEY=<your API key>
50
+ ```
46
51
 
47
52
  ## Rails (ActionMailer)
48
53
 
49
54
  ```ruby
50
55
  # config/environments/production.rb
51
56
  config.action_mailer.delivery_method = :onebillion
52
- config.action_mailer.onebillion_settings = { api_key: ENV["ONEBILLION_KEY"] }
53
57
  ```
54
58
 
55
- That is all. Your mailers and views do not change:
59
+ That is all. The key comes from `ONEBILLION_API_KEY`. Your mailers and views do not change:
56
60
 
57
61
  ```ruby
58
62
  class UserMailer < ApplicationMailer
@@ -70,15 +74,73 @@ The gem sends the finished MIME message to every recipient (`to`, `cc` and `bcc`
70
74
  the `Idempotency-Key`: the same message sent twice goes out once. Send with `deliver_later`, so a slow
71
75
  network never holds a web request.
72
76
 
77
+ To set the key in code, use `onebillion_settings`. The settings win over the environment:
78
+
79
+ ```ruby
80
+ config.action_mailer.onebillion_settings = { api_key: Rails.application.credentials.onebillion_api_key }
81
+ ```
82
+
73
83
  | Setting | Default | What |
74
84
  |---|---|---|
75
- | `api_key` | (required) | the API key of the app |
76
- | `url` | `https://1billion.clowk.in` | another console, for example a dev stack |
85
+ | `api_key` | `ENV["ONEBILLION_API_KEY"]` | the API key of the app |
86
+ | `url` | `ENV["ONEBILLION_URL"]`, else `https://1billion.clowk.in` | another console, for example a dev stack |
87
+
88
+ ## Send a mail (the same call as Resend)
89
+
90
+ ```ruby
91
+ answer = OneBillion::Emails.send(
92
+ {
93
+ from: "Acme <hi@acme.com>",
94
+ to: "jane@example.com",
95
+ subject: "Your code",
96
+ html: "<p>Your code is <b>482 913</b></p>"
97
+ },
98
+ { idempotency_key: "login-jane-482913" }
99
+ )
100
+
101
+ answer["id"] # => "9f2c…", the id of the first message
102
+ ```
103
+
104
+ This is the call of `Resend::Emails.send`: a move from Resend changes only the constant. The keys are
105
+ `from`, `to`, `cc`, `bcc`, `reply_to`, `subject`, `html`, `text`, `attachments` and `priority`, as symbols or
106
+ strings. The answer has `"id"` and `"messages"` (one per recipient).
107
+
108
+ A key that 1billion does not support (for example `tags`, `headers` or `scheduled_at`) raises an
109
+ `ArgumentError` that names it. The SDK never drops a key and sends the mail without it.
110
+
111
+ The key comes from `ONEBILLION_API_KEY`. To set it in code, use `OneBillion.api_key = "..."` (and
112
+ `OneBillion.url` for another console).
113
+
114
+ ## Verify a webhook
115
+
116
+ ```ruby
117
+ class WebhooksController < ApplicationController
118
+ skip_forgery_protection
119
+
120
+ def create
121
+ event = OneBillion::Signature.verify(payload: request.raw_post, headers: request.headers)
122
+
123
+ case event["type"]
124
+ when "bounced" then User.find_by(email: event["to"])&.update(email_bounced: true)
125
+ end
126
+
127
+ head :ok
128
+ rescue OneBillion::Signature::Invalid
129
+ head :unauthorized
130
+ end
131
+ end
132
+ ```
133
+
134
+ `verify` checks `1B-Signature` against the raw body and `1B-Timestamp`, and returns the event as a Hash
135
+ (`id`, `type`, `message_id`, `to`, `detail`, `created_at`). The secret comes from
136
+ `ONEBILLION_WEBHOOK_SECRET`; pass `secret:` to set it in code. A bad or missing signature, or a timestamp older
137
+ than 5 minutes (`tolerance: 300`), raises `OneBillion::Signature::Invalid`. `headers` is a Hash (names in any
138
+ case) or Rails `request.headers`.
77
139
 
78
140
  ## The client
79
141
 
80
142
  ```ruby
81
- client = OneBillion::Client.new(api_key: ENV["ONEBILLION_KEY"])
143
+ client = OneBillion::Client.new # the key of ONEBILLION_API_KEY
82
144
 
83
145
  answer = client.send_mail(
84
146
  from: "Acme <hi@acme.com>",
@@ -170,8 +232,8 @@ No other error is tried again, because a second try gives the same answer.
170
232
 
171
233
  ```ruby
172
234
  OneBillion::Client.new(
173
- api_key: ENV["ONEBILLION_KEY"],
174
- url: "http://localhost:3100", # https://1billion.clowk.in by default
235
+ api_key: "...", # ENV["ONEBILLION_API_KEY"] by default
236
+ url: "http://localhost:3100", # ENV["ONEBILLION_URL"], else https://1billion.clowk.in
175
237
  timeout: 5, # seconds, 10 by default
176
238
  backoff: 1 # the first wait between tries, 0.5 s by default
177
239
  )
@@ -7,7 +7,7 @@ module OneBillion
7
7
  # The client of the 1billion API. Use it only on a server: an API key must never reach a
8
8
  # browser.
9
9
  #
10
- # client = OneBillion::Client.new(api_key: ENV["ONEBILLION_KEY"])
10
+ # client = OneBillion::Client.new # the key of ENV["ONEBILLION_API_KEY"]
11
11
  # client.send_mail(from: "App <hi@app.com>", to: ["ana@example.com"], subject: "Oi", text: "Olá")
12
12
  #
13
13
  # A 503 or a network error is tried again (3 times in all) with the same Idempotency-Key, so
@@ -18,8 +18,8 @@ module OneBillion
18
18
 
19
19
  # agent: a word added to the User-Agent (the delivery method of ActionMailer adds
20
20
  # "actionmailer"), so the console shows where a mail came from.
21
- def initialize(api_key:, url: DEFAULT_URL, timeout: 10, backoff: 0.5, transport: nil, agent: nil)
22
- raise ArgumentError, "api_key is required" if api_key.to_s.empty?
21
+ def initialize(api_key: OneBillion.api_key, url: OneBillion.url, timeout: 10, backoff: 0.5, transport: nil, agent: nil)
22
+ raise ArgumentError, "no API key: set ONEBILLION_API_KEY or pass api_key:" if api_key.to_s.empty?
23
23
 
24
24
  @api_key = api_key
25
25
  @agent = agent
@@ -2,7 +2,9 @@ module OneBillion
2
2
  # The ActionMailer delivery method. Your mailers stay as they are:
3
3
  #
4
4
  # config.action_mailer.delivery_method = :onebillion
5
- # config.action_mailer.onebillion_settings = { api_key: ENV["ONEBILLION_KEY"] }
5
+ #
6
+ # The API key comes from ENV["ONEBILLION_API_KEY"]. The optional `onebillion_settings`
7
+ # (`api_key:`, `url:`) win over the environment.
6
8
  #
7
9
  # It sends the finished MIME message (`raw`) to every envelope recipient (to, cc and bcc; Bcc
8
10
  # is not in the message). The Message-ID is the Idempotency-Key, so a retried job never sends
@@ -21,7 +23,7 @@ module OneBillion
21
23
  private
22
24
 
23
25
  def client
24
- @client ||= Client.new(api_key: settings.fetch(:api_key), url: settings.fetch(:url, Client::DEFAULT_URL), agent: "actionmailer")
26
+ @client ||= Client.new(api_key: settings[:api_key] || OneBillion.api_key, url: settings[:url] || OneBillion.url, agent: "actionmailer")
25
27
  end
26
28
  end
27
29
  end
@@ -0,0 +1,33 @@
1
+ module OneBillion
2
+ # The same call as Resend::Emails.send, so a move from Resend changes only the constant:
3
+ #
4
+ # OneBillion::Emails.send({ from: "App <hi@app.com>", to: "ana@example.com", subject: "Oi", html: "<p>Olá</p>" })
5
+ # # => { "id" => "9f2c…", "messages" => [{ "id" => "9f2c…", "to" => "ana@example.com", "status" => "accepted" }] }
6
+ #
7
+ # A key that 1billion does not support (for example `tags` or `scheduled_at`) raises an
8
+ # ArgumentError: the mail is never sent without it.
9
+ module Emails
10
+ FIELDS = %i[from to cc bcc reply_to subject html text attachments priority].freeze
11
+ OPTIONS = %i[idempotency_key].freeze
12
+
13
+ def self.send(params, options = {})
14
+ params = symbolize(params, FIELDS, "OneBillion::Emails.send")
15
+ options = symbolize(options, OPTIONS, "the options of OneBillion::Emails.send")
16
+
17
+ answer = OneBillion.client.send_mail(**params, **options)
18
+
19
+ { "id" => answer.fetch("messages", []).first&.fetch("id"), **answer }
20
+ end
21
+
22
+ def self.symbolize(hash, allowed, name)
23
+ hash = hash.to_h { |key, value| [key.to_sym, value] }
24
+ unknown = hash.keys - allowed
25
+
26
+ raise ArgumentError, "#{name} does not support: #{unknown.join(", ")}" if unknown.any?
27
+
28
+ hash
29
+ end
30
+
31
+ private_class_method :symbolize
32
+ end
33
+ end
@@ -0,0 +1,46 @@
1
+ require "json"
2
+ require "openssl"
3
+
4
+ module OneBillion
5
+ # Checks the signature of a webhook and returns the event:
6
+ #
7
+ # event = OneBillion::Signature.verify(payload: request.raw_post, headers: request.headers)
8
+ # event["type"] # => "delivered"
9
+ #
10
+ # The signature is `1B-Signature: sha256=<hex>`, with hex = HMAC-SHA256(secret,
11
+ # "<1B-Timestamp>.<raw body>"). The secret comes from ENV["ONEBILLION_WEBHOOK_SECRET"].
12
+ module Signature
13
+ # A bad or missing signature, or a timestamp out of the tolerance.
14
+ class Invalid < Error; end
15
+
16
+ def self.verify(payload:, headers:, secret: ENV["ONEBILLION_WEBHOOK_SECRET"], tolerance: 300)
17
+ raise ArgumentError, "no webhook secret: set ONEBILLION_WEBHOOK_SECRET or pass secret:" if secret.to_s.empty?
18
+
19
+ timestamp = header(headers, "1B-Timestamp").to_s
20
+ signature = header(headers, "1B-Signature").to_s
21
+
22
+ raise Invalid, "no 1B-Timestamp or 1B-Signature header" if timestamp.empty? || signature.empty?
23
+
24
+ seconds = Integer(timestamp, 10, exception: false)
25
+
26
+ raise Invalid, "the timestamp is out of the tolerance" if seconds.nil? || (Time.now.to_i - seconds).abs > tolerance
27
+
28
+ expected = "sha256=#{OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.#{payload}")}"
29
+
30
+ raise Invalid, "the signature does not match" unless OpenSSL.secure_compare(expected, signature)
31
+
32
+ JSON.parse(payload)
33
+ end
34
+
35
+ # A Hash with names in any case, or an object with [] such as Rails request.headers.
36
+ def self.header(headers, name)
37
+ value = headers[name]
38
+
39
+ return value if value || !headers.is_a?(Hash)
40
+
41
+ headers.find { |key, _| key.to_s.casecmp?(name) }&.last
42
+ end
43
+
44
+ private_class_method :header
45
+ end
46
+ end
@@ -1,3 +1,3 @@
1
1
  module OneBillion
2
- VERSION = "0.1.0"
2
+ VERSION = "0.3.0"
3
3
  end
data/lib/onebillion.rb CHANGED
@@ -2,9 +2,35 @@ require_relative "onebillion/version"
2
2
  require_relative "onebillion/errors"
3
3
  require_relative "onebillion/client"
4
4
  require_relative "onebillion/delivery_method"
5
+ require_relative "onebillion/emails"
6
+ require_relative "onebillion/signature"
5
7
 
6
- # 1billion: transactional e-mail. See OneBillion::Client and OneBillion::DeliveryMethod.
8
+ # 1billion: transactional e-mail. See OneBillion::Client, OneBillion::Emails,
9
+ # OneBillion::Signature and OneBillion::DeliveryMethod.
10
+ #
11
+ # The API key comes from ENV["ONEBILLION_API_KEY"] and the base URL from ENV["ONEBILLION_URL"],
12
+ # unless you set OneBillion.api_key or OneBillion.url.
7
13
  module OneBillion
14
+ class << self
15
+ def api_key = @api_key || ENV["ONEBILLION_API_KEY"]
16
+
17
+ def url = @url || ENV["ONEBILLION_URL"] || Client::DEFAULT_URL
18
+
19
+ def api_key=(value)
20
+ @api_key = value
21
+ @client = nil
22
+ end
23
+
24
+ def url=(value)
25
+ @url = value
26
+ @client = nil
27
+ end
28
+
29
+ # The client of OneBillion::Emails, made from OneBillion.api_key and OneBillion.url.
30
+ attr_writer :client
31
+
32
+ def client = @client ||= Client.new
33
+ end
8
34
  end
9
35
 
10
36
  if defined?(ActionMailer)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: 1billion
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Thadeu Esteves
@@ -19,7 +19,9 @@ files:
19
19
  - lib/onebillion.rb
20
20
  - lib/onebillion/client.rb
21
21
  - lib/onebillion/delivery_method.rb
22
+ - lib/onebillion/emails.rb
22
23
  - lib/onebillion/errors.rb
24
+ - lib/onebillion/signature.rb
23
25
  - lib/onebillion/version.rb
24
26
  homepage: https://1billion.clowk.in
25
27
  licenses: