mailset 0.7.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,475 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # Mailset took the message: what {Client#send_email} answers.
5
+ class Sent < Model
6
+ # @!attribute [r] ok
7
+ # Always true: Mailset took it. Also {#ok?}.
8
+ # @return [true]
9
+ field :ok, 'ok', [:literal, true], required: true
10
+
11
+ # @!attribute [r] id
12
+ # Mailset's id for this send.
13
+ # @return [String]
14
+ field :id, 'id', :string, required: true
15
+
16
+ # @!attribute [r] message_id
17
+ # The Message-ID header, without its angle brackets.
18
+ # @return [String]
19
+ field :message_id, 'messageId', :string, required: true
20
+
21
+ # @!attribute [r] status
22
+ # `sent`: it went. `queued`: Mailset holds it and sends it at
23
+ # {#sends_at}, because a sending limit needs time to make room or the
24
+ # provider stumbled. Nothing to do either way.
25
+ # @return [String]
26
+ field :status, 'status', :ReceiptState, required: true
27
+
28
+ # @!attribute [r] state
29
+ # The same as {#status}.
30
+ # @return [String]
31
+ field :state, 'state', :ReceiptState, required: true
32
+
33
+ # @!attribute [r] sends_at
34
+ # When a queued message should go out, in ms since the epoch.
35
+ # @return [Integer, nil]
36
+ field :sends_at, 'sendsAt', :integer
37
+
38
+ # @!attribute [r] reason
39
+ # Why a queued message waits, in words for people.
40
+ # @return [String, nil]
41
+ field :reason, 'reason', :string
42
+
43
+ # @!attribute [r] skipped
44
+ # Recipients Mailset skipped (an Apple Hide My Email address, a
45
+ # temporary inbox, someone who unsubscribed from promotional mail): they
46
+ # never get it, the others do. Nothing to retry. When it names every
47
+ # recipient, nothing went out, so ask the person for another address.
48
+ # Nil when nobody was skipped.
49
+ # @return [Array<Mailset::SkippedRecipient>, nil]
50
+ field :skipped, 'skipped', [:array, :SkippedRecipient]
51
+
52
+ # Always true.
53
+ def ok?
54
+ true
55
+ end
56
+ end
57
+
58
+ # Mailset refused this one message of a batch: what {Client#send_emails}
59
+ # answers in its place. The rest are unaffected.
60
+ class NotSent
61
+ # Null when the message couldn't even be built.
62
+ # @return [String, nil]
63
+ attr_reader :message_id
64
+
65
+ # Why.
66
+ # @return [Mailset::Error]
67
+ attr_reader :error
68
+
69
+ def initialize(message_id, error)
70
+ @message_id = message_id
71
+ @error = error
72
+ end
73
+
74
+ # Always false.
75
+ def ok
76
+ false
77
+ end
78
+
79
+ # Always false.
80
+ def ok?
81
+ false
82
+ end
83
+
84
+ # @return [Hash{String => Object}]
85
+ def to_h
86
+ { 'ok' => false, 'messageId' => message_id, 'error' => error.to_h }
87
+ end
88
+
89
+ def to_json(*args)
90
+ to_h.to_json(*args)
91
+ end
92
+
93
+ def deconstruct_keys(_keys)
94
+ { ok: false, message_id: message_id, error: error }
95
+ end
96
+
97
+ def inspect
98
+ "#<Mailset::NotSent message_id=#{message_id.inspect} error=#{error.inspect}>"
99
+ end
100
+ alias to_s inspect
101
+ end
102
+
103
+ # This client's key: `mailset.key`.
104
+ class KeyApi
105
+ # @api private
106
+ def initialize(transport)
107
+ @transport = transport
108
+ end
109
+
110
+ # Proves the key still works and keeps it alive: a key unused for 90 days
111
+ # stops. Call it when your server starts and once a day, so a product that
112
+ # sends rarely never loses its key, and a revoked one shows in your logs
113
+ # before a customer misses an email. Calls `grants.current`.
114
+ #
115
+ # The status names the key's mailboxes (a mailbox key's) and its domains
116
+ # (a domain key's sending-only domain), each with its sending state. A
117
+ # server from before domain keys sends no `domains`: it reads as `[]`.
118
+ # @return [Mailset::KeyStatus]
119
+ def check
120
+ data = @transport.command('grants.current', {})
121
+ unless data.is_a?(Hash) && data['name'].is_a?(String) && data['expiresAt'].is_a?(Integer) &&
122
+ data['mailboxes'].is_a?(Array)
123
+ raise ServerError.new('The Mailset API can’t be reached.', code: 'unavailable', command: 'grants.current')
124
+ end
125
+
126
+ KeyStatus.from_json(data)
127
+ end
128
+
129
+ def inspect
130
+ '#<Mailset::KeyApi>'
131
+ end
132
+ end
133
+
134
+ # A client for one credential: a MAILSET_KEY (an app's) or a MAILSET_TOKEN
135
+ # (a person's), given or read from the environment. Nothing is sent until
136
+ # you call a method. One client is safe to share between threads.
137
+ #
138
+ # mailset = Mailset::Client.new
139
+ # mailset.send_email(from: 'Acme <hello@example.com>', to: 'ana@example.org',
140
+ # subject: 'Your code', text: 'Your code is 123456.')
141
+ # mailset.domains.add(name: 'example.com') # every public command, in its group
142
+ #
143
+ # Every generated method takes `request_options:` beside its own keywords:
144
+ # `org:` (the org it's about, for a person in several), `approval:` (a
145
+ # passkey approval's id) and `timeout:` (seconds per try).
146
+ class Client
147
+ include Resources::Calls
148
+ include Resources::Root
149
+
150
+ # The most messages one `messages.submitMany` takes.
151
+ MAX_SUBMIT_MESSAGES = 100
152
+ # The messages of one call, all together, before base64.
153
+ MAX_SUBMIT_BYTES = 48 * 1024 * 1024
154
+ # A whole call failing this way says nothing about any one message: the key or the network.
155
+ CALL_FAILURES = %w[unauthorized forbidden unavailable internal].freeze
156
+ UNITS = { 's' => 1000, 'm' => 60_000, 'h' => 3_600_000, 'd' => 86_400_000 }.freeze
157
+
158
+ # With nothing given, it reads MAILSET_KEY, else MAILSET_TOKEN, from the
159
+ # environment.
160
+ #
161
+ # @param key [String, nil] MAILSET_KEY (`msk1_…`), an app key: sends as the
162
+ # mailboxes its grant names. An API token works here too.
163
+ # @param token [String, nil] MAILSET_TOKEN (`mst_…`), an API token: a
164
+ # person's, for the commands no app key can run, such as `domains.add`.
165
+ # @param base_url [String, nil] where Mailset is. Unless given, MAILSET_API,
166
+ # else the key's own, else https://mailset.app.
167
+ # @param org [String, nil] the org a command is about, for a person in more
168
+ # than one. Each call may name another.
169
+ # @param timeout [Numeric] how long one try of a call may take, in seconds:
170
+ # 30 unless told. A call may name its own (`request_options: { timeout: }`).
171
+ # When every try runs out of time, the call raises {TimeoutError}.
172
+ # @param max_retries [Integer] how many times a call is tried again after a
173
+ # network failure, a dropped connection, a try that ran out of time or a
174
+ # 5xx, waiting longer each time (0.5 s doubling to 8 s, with jitter, or
175
+ # what Retry-After asks); never after a 4xx. 2 unless told; 0 never. A
176
+ # send is safe to try again with no idempotency_key: every try sends the
177
+ # same bytes, so it keeps its Message-ID and Mailset sends it once.
178
+ # @param on_approval [#call, nil] called with a {Mailset::Approval} when a
179
+ # command needs a passkey: open its `url` (or send it to whoever
180
+ # approves), and the call goes on once they do. Without it, such a command
181
+ # raises {PasskeyRequiredError} with the purpose to approve.
182
+ # @param http [#call, nil] your own HTTP adapter, for tests or a proxy: it
183
+ # takes a {HttpRequest} and answers a {HttpResponse}.
184
+ # @param now [#call, nil] the clock every request is signed with, answering
185
+ # a Time. Only tests change it.
186
+ # @raise [Mailset::InvalidRequestError] when there's no credential, or what's
187
+ # given isn't one.
188
+ def initialize(key: nil, token: nil, base_url: nil, org: nil, timeout: 30, max_retries: 2, on_approval: nil,
189
+ http: nil, now: nil)
190
+ credential = Credential.find(key: key, token: token)
191
+ @transport = Transport.new(credential, base_url: base_url, org: org, timeout: timeout,
192
+ max_retries: max_retries, http: http, now: now, on_approval: on_approval)
193
+ end
194
+
195
+ # Where this client sends its calls.
196
+ # @return [String]
197
+ def base_url
198
+ transport.base_url
199
+ end
200
+
201
+ # The org a command is about unless a call names another.
202
+ # @return [String, nil]
203
+ def org
204
+ transport.org
205
+ end
206
+
207
+ # Which credential this client holds: `:key` (a MAILSET_KEY) or `:token`
208
+ # (a MAILSET_TOKEN). Nothing of the credential itself.
209
+ # @return [Symbol]
210
+ def credential_kind
211
+ transport.credential.kind
212
+ end
213
+
214
+ # Sends one message: its receipt, or the refusal raised. The client builds
215
+ # the whole message (MIME, encoded names, a text and an HTML part, files)
216
+ # and submits it with `messages.submitMany`.
217
+ #
218
+ # Mail to an Apple Hide My Email address or a temporary inbox, and
219
+ # promotional mail to someone who unsubscribed from its mailbox, isn't
220
+ # refused: the receipt's `skipped` names each one, and it goes to everyone
221
+ # else.
222
+ #
223
+ # Ruby calls it `send_email`, since `send` is a method every Ruby object has.
224
+ #
225
+ # @param from [String, Hash] a mailbox this key may send as:
226
+ # `'Acme <hello@example.com>'`, `'hello@example.com'`, or `{ name:, email: }`.
227
+ # @param to [String, Hash, Array<String, Hash>]
228
+ # @param subject [String]
229
+ # @param text [String]
230
+ # @param cc [String, Hash, Array<String, Hash>, nil]
231
+ # @param bcc [String, Hash, Array<String, Hash>, nil] never shown to anyone:
232
+ # Mailset takes it out before the message leaves.
233
+ # @param reply_to [String, Hash, Array<String, Hash>, nil]
234
+ # @param html [String, nil] a designed version. Without it, the text is
235
+ # wrapped in plain HTML.
236
+ # @param attachments [Array<Hash>, nil] each `{ filename:, content_type:,
237
+ # content: }` (a String of bytes or an IO), or `base64:` or `path:` for
238
+ # the bytes.
239
+ # @param headers [Hash{String => String}, nil] extra headers, such as your
240
+ # own `List-Unsubscribe`. Addressing, subject, dates and MIME headers are
241
+ # Mailset's and can't be set here.
242
+ # @param mode [String, nil] `transactional` (the default: a sign-in code, a
243
+ # receipt, an alert) or `promotional` (a newsletter, an offer: one
244
+ # address in `to`, and Mailset adds a one-click unsubscribe where you
245
+ # write `{{mailset_unsubscribe}}`, or as a last line).
246
+ # @param keep_copy [Boolean] keep a copy in the mailbox's Sent folder, like
247
+ # mail a person writes. Off by default: a product's mail leaves only its
248
+ # delivery log.
249
+ # @param deliver_by [Time, String, ActiveSupport::Duration, nil] the latest it
250
+ # may go out: a Time, or a time from now such as `'30s'`, `'10m'`, `'2h'`
251
+ # or `'1d'` (or `10.minutes` in Rails). Mail a limit would hold past it is
252
+ # refused at once (`limit_reached`, with `retry_at`), and mail still
253
+ # waiting when it comes is dropped and shows as `expired`.
254
+ # @param idempotency_key [String, nil] a name of your own for this one send,
255
+ # such as `receipt-8842`, so sending it again can't send it twice. After a
256
+ # timeout or a crash, send again with the same key: Mailset answers the
257
+ # first send's receipt and sends nothing new. 1 to 255 characters, no
258
+ # line breaks. A key belongs to its `from` address and has no time limit.
259
+ # @return [Mailset::Sent]
260
+ # @raise [Mailset::Error] when Mailset refuses it, can't be reached, or the
261
+ # message can't be built as given (`invalid_input`, before any call).
262
+ def send_email(from:, to:, subject:, text:, cc: nil, bcc: nil, reply_to: nil, html: nil, attachments: nil,
263
+ headers: nil, mode: nil, keep_copy: false, deliver_by: nil, idempotency_key: nil)
264
+ message = prepare(
265
+ { from: from, to: to, subject: subject, text: text, cc: cc, bcc: bcc, reply_to: reply_to, html: html,
266
+ attachments: attachments, headers: headers, mode: mode, keep_copy: keep_copy, deliver_by: deliver_by,
267
+ idempotency_key: idempotency_key },
268
+ transport.now_ms
269
+ )
270
+ result = submit([message]).first
271
+ raise result.error unless result.ok?
272
+
273
+ result
274
+ end
275
+
276
+ # Sends many messages, each a Hash of {#send_email}'s keywords: one result
277
+ # each, in the same order, a {Sent} or a {NotSent}. A refusal is that
278
+ # message's result and never stops the rest, and neither is a message that
279
+ # can't be built.
280
+ #
281
+ # Any number goes: past 100 messages, or 48 MB, they go in several calls.
282
+ # It raises only when the credential is refused or Mailset can't be reached
283
+ # before any message was taken, or when two messages carry the same
284
+ # `idempotency_key` from the same address (`invalid_input`, before
285
+ # anything is sent).
286
+ #
287
+ # results = mailset.send_emails([
288
+ # { from: 'hello@example.com', to: 'ana@example.org', subject: 'Invoice', text: '…' },
289
+ # { from: 'hello@example.com', to: 'ben@example.org', subject: 'Invoice', text: '…' }
290
+ # ])
291
+ # results.each { |result| puts result.ok? ? result.id : result.error.code }
292
+ #
293
+ # @param messages [Array<Hash>]
294
+ # @return [Array<Mailset::Sent, Mailset::NotSent>]
295
+ def send_emails(messages)
296
+ raise ArgumentError, 'send_emails takes an Array of messages' unless messages.respond_to?(:each_with_index)
297
+
298
+ results = []
299
+ ready = []
300
+ keys = []
301
+ messages.each_with_index do |fields, index|
302
+ given = Mime.fields_of(fields, %i[mode keep_copy deliver_by idempotency_key])
303
+ keys[index] = given[:idempotency_key]
304
+ begin
305
+ ready << [index, prepare(given, transport.now_ms)]
306
+ rescue Error => e
307
+ results[index] = NotSent.new(nil, e)
308
+ end
309
+ end
310
+ keys_once!(keys, ready)
311
+ deliver(ready, results)
312
+ results
313
+ end
314
+
315
+ # This client's key: `mailset.key.check`.
316
+ # @return [Mailset::KeyApi]
317
+ def key
318
+ @key ||= KeyApi.new(transport)
319
+ end
320
+
321
+ # Events from your org's hook: the same module as {Mailset::Webhooks}.
322
+ # @return [Module]
323
+ def webhooks
324
+ Webhooks
325
+ end
326
+
327
+ # Approvals for commands that need a passkey.
328
+ # @return [Mailset::Approvals]
329
+ def approvals
330
+ transport.approvals
331
+ end
332
+
333
+ # Any command by its id, with its input as Mailset takes it (camelCase):
334
+ # for one this gem has no method for yet. Answers its `data` as parsed JSON.
335
+ # @param command [String] such as `'domains.add'`
336
+ # @param input [Hash]
337
+ # @return [Object]
338
+ def request(command, input = {}, org: nil, approval: nil, timeout: nil)
339
+ transport.command(command.to_s, Types.plain(input || {}), org: org, approval: approval, timeout: timeout)
340
+ end
341
+
342
+ # Names the credential's kind and where it goes, nothing of the credential.
343
+ def inspect
344
+ "#<Mailset::Client #{transport.credential.variable} #{base_url}>"
345
+ end
346
+ alias to_s inspect
347
+
348
+ private
349
+
350
+ attr_reader :transport
351
+
352
+ # One message, ready for `messages.submitMany`: [message_id, bytes, body].
353
+ def prepare(fields, now)
354
+ id = fields[:idempotency_key].nil? ? nil : Mime.idempotent_id(fields[:idempotency_key], fields[:from])
355
+ raw, message_id = Mime.build(fields, Time.at(now / 1000r), id)
356
+ bytes = raw.bytesize
357
+ raise RateLimitError, 'That message is larger than 20 MB.' if bytes > Mime::MAX_MESSAGE_BYTES
358
+
359
+ body = { 'data' => Base64url.strict_encode(raw), 'transactional' => !fields[:keep_copy] }
360
+ body['mode'] = fields[:mode].to_s unless fields[:mode].nil?
361
+ deadline = deadline_of(fields[:deliver_by], now)
362
+ body['deliverBy'] = deadline unless deadline.nil?
363
+ [message_id, bytes, body]
364
+ end
365
+
366
+ # `deliver_by` as Mailset takes it: ms since the epoch.
367
+ def deadline_of(value, now)
368
+ return nil if value.nil?
369
+
370
+ if value.is_a?(String)
371
+ match = value.match(/\A\s*(\d+)\s*([smhd])\s*\z/)
372
+ return now + (match[1].to_i * UNITS[match[2]]) if match
373
+ elsif defined?(::ActiveSupport::Duration) && value.is_a?(::ActiveSupport::Duration)
374
+ return now + (value.to_f * 1000).round
375
+ elsif Types.time?(value) || value.is_a?(::Date)
376
+ return Types.ms(value)
377
+ end
378
+ raise InvalidRequestError, 'deliver_by takes a Time, or a time from now like 30s, 10m or 2h.'
379
+ end
380
+
381
+ # A key names one send, so a batch that carries one twice from the same
382
+ # address is wrong as a whole: the second could only be dropped in silence.
383
+ def keys_once!(keys, ready)
384
+ seen = Hash.new { |hash, id| hash[id] = [] }
385
+ ready.each { |index, (message_id, _, _)| seen[message_id] << index unless keys[index].nil? }
386
+ seen.each_value do |indexes|
387
+ next if indexes.length < 2
388
+
389
+ where = "#{indexes[0...-1].join(', ')} and #{indexes[-1]}"
390
+ raise InvalidRequestError,
391
+ "idempotency_key #{keys[indexes[0]].inspect} is on more than one message of this batch: items " \
392
+ "#{where}, counted from 0. A key names one send, so give each message its own. Nothing was sent."
393
+ end
394
+ end
395
+
396
+ def deliver(ready, results)
397
+ taken = false
398
+ chunks_of(ready).each do |chunk|
399
+ begin
400
+ answers = submit(chunk.map(&:last))
401
+ chunk.each_with_index { |(index, _), at| results[index] = answers[at] }
402
+ taken = true
403
+ rescue Error => e
404
+ # Once Mailset took some, the answer must say which: a later failure lands on each message.
405
+ raise if !taken && CALL_FAILURES.include?(e.code)
406
+
407
+ chunk.each { |index, (message_id, _, _)| results[index] = NotSent.new(message_id, e) }
408
+ end
409
+ end
410
+ end
411
+
412
+ # Calls of at most 100 messages and 48 MB, in order.
413
+ def chunks_of(ready)
414
+ chunks = []
415
+ current = []
416
+ bytes = 0
417
+ ready.each do |item|
418
+ size = item[1][1]
419
+ if current.length == MAX_SUBMIT_MESSAGES || (!current.empty? && bytes + size > MAX_SUBMIT_BYTES)
420
+ chunks << current
421
+ current = []
422
+ bytes = 0
423
+ end
424
+ current << item
425
+ bytes += size
426
+ end
427
+ chunks << current unless current.empty?
428
+ chunks
429
+ end
430
+
431
+ # One `messages.submitMany`: a result per message, in order.
432
+ def submit(messages)
433
+ data = transport.command('messages.submitMany', { 'messages' => messages.map(&:last) })
434
+ results = data.is_a?(Hash) ? data['results'] : nil
435
+ raise unreachable unless results.is_a?(Array) && results.length == messages.length
436
+
437
+ results.each_with_index.map { |value, at| result_of(value, messages[at][0]) }
438
+ end
439
+
440
+ def result_of(value, message_id)
441
+ raise unreachable unless value.is_a?(Hash)
442
+ return NotSent.new(message_id, Error.from_body(value['error']) || unreachable) if value['ok'] == false
443
+
444
+ state = value['state']
445
+ unless value['ok'] == true && value['id'].is_a?(String) && value['sendAt'].is_a?(Numeric) &&
446
+ %w[sent queued].include?(state)
447
+ raise unreachable
448
+ end
449
+
450
+ fields = { ok: true, id: value['id'], message_id: message_id, status: state, state: state }
451
+ if state == 'queued'
452
+ fields[:sends_at] = value['sendAt']
453
+ fields[:reason] = value['held'] if value['held'].is_a?(String)
454
+ end
455
+ skipped = skipped_of(value['skipped'])
456
+ fields[:skipped] = skipped unless skipped.empty?
457
+ Sent.new(**fields)
458
+ end
459
+
460
+ # The skipped recipients of a receipt; one with a reason this version doesn't know still counts.
461
+ def skipped_of(value)
462
+ return [] unless value.is_a?(Array)
463
+
464
+ value.filter_map do |item|
465
+ next unless item.is_a?(Hash) && item['address'].is_a?(String) && item['reason'].is_a?(String)
466
+
467
+ SkippedRecipient.new(address: item['address'], reason: item['reason'])
468
+ end
469
+ end
470
+
471
+ def unreachable(command = 'messages.submitMany')
472
+ ServerError.new('The Mailset API can’t be reached.', code: 'unavailable', command: command)
473
+ end
474
+ end
475
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # A credential, decoded: which kind it is (`:key`, an app's MAILSET_KEY, or
5
+ # `:token`, a person's MAILSET_TOKEN), the API it names, its session token,
6
+ # and the P-256 key that signs every request. Its string form names the
7
+ # kind and nothing of it.
8
+ #
9
+ # @api private
10
+ class Credential
11
+ KEY_PREFIX = 'msk1_'
12
+ TOKEN_PREFIX = 'mst_'
13
+
14
+ NO_CREDENTIAL = 'No credential: set MAILSET_KEY (an app key: npx @mailset/cli keys create --send ' \
15
+ '--mailbox <address>) or MAILSET_TOKEN (an API token: npx @mailset/cli tokens create ' \
16
+ '"<name>"), or pass key: or token:.'
17
+ NOT_A_KEY = 'That isn’t a MAILSET_KEY. Make one with: npx @mailset/cli keys create --send --mailbox <address>'
18
+ NOT_A_TOKEN = 'That isn’t a MAILSET_TOKEN. Make one with: npx @mailset/cli tokens create "<name>"'
19
+
20
+ # @return [Symbol] `:key` or `:token`
21
+ attr_reader :kind
22
+ # @return [String, nil] the API a key names
23
+ attr_reader :api
24
+
25
+ # The credential given, else the environment's MAILSET_KEY, else its
26
+ # MAILSET_TOKEN. Raises {InvalidRequestError} when there is none, or
27
+ # what's there isn't one; never with the text itself.
28
+ def self.find(key: nil, token: nil, env: ENV)
29
+ text = [key, token, env['MAILSET_KEY'], env['MAILSET_TOKEN']].find { |one| one.is_a?(String) && !one.strip.empty? }
30
+ raise InvalidRequestError, NO_CREDENTIAL unless text
31
+
32
+ parse(text) || raise(InvalidRequestError, text.strip.start_with?(TOKEN_PREFIX) ? NOT_A_TOKEN : NOT_A_KEY)
33
+ end
34
+
35
+ # A MAILSET_KEY or MAILSET_TOKEN, whichever the text is, or nil.
36
+ def self.parse(text)
37
+ value = text.to_s.strip
38
+ if value.start_with?(KEY_PREFIX)
39
+ fields = decoded(value.delete_prefix(KEY_PREFIX))
40
+ return nil unless fields && filled?(fields['api']) && url?(fields['api'])
41
+
42
+ build(:key, fields['api'], fields)
43
+ elsif value.start_with?(TOKEN_PREFIX)
44
+ fields = decoded(value.delete_prefix(TOKEN_PREFIX))
45
+ return nil unless fields
46
+
47
+ build(:token, fields['api'].is_a?(String) ? fields['api'] : nil, fields)
48
+ end
49
+ end
50
+
51
+ def self.decoded(text)
52
+ bytes = Base64url.decode(text)
53
+ return nil unless bytes
54
+
55
+ fields = JSON.parse(bytes.force_encoding('UTF-8'))
56
+ fields.is_a?(Hash) ? fields : nil
57
+ rescue JSON::ParserError, EncodingError
58
+ nil
59
+ end
60
+
61
+ def self.build(kind, api, fields)
62
+ jwk = fields['privateKey']
63
+ return nil unless filled?(fields['token']) && jwk.is_a?(Hash) && jwk['kty'] == 'EC'
64
+ return nil unless jwk['crv'].nil? || jwk['crv'] == 'P-256'
65
+
66
+ signer = signer_of(jwk['d'])
67
+ signer && new(kind, api, fields['token'], signer)
68
+ end
69
+
70
+ def self.filled?(value)
71
+ value.is_a?(String) && !value.empty?
72
+ end
73
+
74
+ def self.url?(text)
75
+ uri = URI.parse(text)
76
+ !uri.scheme.nil? && !uri.host.to_s.empty?
77
+ rescue URI::InvalidURIError
78
+ false
79
+ end
80
+
81
+ # The P-256 private key a JWK's `d` is. OpenSSL 3's keys can't be filled
82
+ # in after they're made, so this wraps the scalar in an EC private key's
83
+ # DER (RFC 5915) and loads that.
84
+ def self.signer_of(scalar_text)
85
+ scalar = Base64url.decode(scalar_text.to_s)
86
+ return nil if scalar.nil? || scalar.empty? || scalar.bytesize > 32
87
+
88
+ der = OpenSSL::ASN1::Sequence([
89
+ OpenSSL::ASN1::Integer(1),
90
+ OpenSSL::ASN1::OctetString(scalar.rjust(32, "\0".b)),
91
+ OpenSSL::ASN1::ObjectId('prime256v1', 0, :EXPLICIT)
92
+ ]).to_der
93
+ OpenSSL::PKey::EC.new(der)
94
+ rescue OpenSSL::OpenSSLError
95
+ nil
96
+ end
97
+ private_class_method :decoded, :build, :filled?, :url?, :signer_of
98
+
99
+ def initialize(kind, api, token, signer)
100
+ @kind = kind
101
+ @api = api
102
+ @token = token
103
+ @signer = signer
104
+ end
105
+ private_class_method :new
106
+
107
+ # `Authorization`'s value.
108
+ def authorization
109
+ "Bearer #{@token}"
110
+ end
111
+
112
+ # `MAILSET_KEY` or `MAILSET_TOKEN`: the variable this kind comes in.
113
+ def variable
114
+ kind == :key ? 'MAILSET_KEY' : 'MAILSET_TOKEN'
115
+ end
116
+
117
+ # An ECDSA P-256 SHA-256 signature of the bytes, as Mailset reads it: r
118
+ # then s, 32 bytes each. OpenSSL answers in DER, so this writes each out.
119
+ def sign(message)
120
+ der = @signer.sign('SHA256', message)
121
+ OpenSSL::ASN1.decode(der).value.map { |number| number.value.to_s(2).rjust(32, "\0".b) }.join
122
+ end
123
+
124
+ # The headers that prove this credential made this request now:
125
+ # `ms-time`, and `ms-proof` over the method, the path with its query, the
126
+ # time and the body's SHA-256. The bytes signed are the bytes sent.
127
+ def proof(method, path, body, now_ms)
128
+ digest = Base64url.encode(OpenSSL::Digest::SHA256.digest(body))
129
+ message = "ms-proof-v1\n#{method.upcase}\n#{path}\n#{now_ms}\n#{digest}"
130
+ { 'ms-time' => now_ms.to_s, 'ms-proof' => Base64url.encode(sign(message.b)) }
131
+ end
132
+
133
+ def inspect
134
+ "#<Mailset::Credential #{variable}>"
135
+ end
136
+ alias to_s inspect
137
+ end
138
+ end