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,497 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # A whole message, built by {Mailset.build_message}: its RFC 5322 text and
5
+ # its Message-ID.
6
+ class BuiltMessage
7
+ # The whole message, CRLF lines, as `messages.submit` takes it once in base64.
8
+ # @return [String]
9
+ attr_reader :raw
10
+
11
+ # The Message-ID header, without its angle brackets.
12
+ # @return [String]
13
+ attr_reader :message_id
14
+
15
+ def initialize(raw, message_id)
16
+ @raw = raw
17
+ @message_id = message_id
18
+ end
19
+
20
+ # The message in standard base64 on one line: `messages.submit`'s `data`.
21
+ # @return [String]
22
+ def base64
23
+ Base64url.strict_encode(raw)
24
+ end
25
+
26
+ def inspect
27
+ "#<Mailset::BuiltMessage message_id=#{message_id.inspect} bytes=#{raw.bytesize}>"
28
+ end
29
+ end
30
+
31
+ # Builds a whole message from its fields, as {Client#send_email} does,
32
+ # without sending it: for `messages.submit` yourself, or to look at.
33
+ #
34
+ # message = Mailset.build_message(from: 'Acme <hello@example.com>', to: 'ana@example.org',
35
+ # subject: 'Your code', text: 'Your code is 123456.')
36
+ # message.raw # the RFC 5322 text
37
+ # message.message_id # "3f…@example.com"
38
+ #
39
+ # The fields are {Client#send_email}'s. With `idempotency_key:`, the
40
+ # Message-ID is the one that key stands for.
41
+ # @return [Mailset::BuiltMessage]
42
+ def self.build_message(from:, to:, subject:, text:, cc: nil, bcc: nil, reply_to: nil, html: nil, attachments: nil,
43
+ headers: nil, idempotency_key: nil, date: Time.now)
44
+ fields = { from: from, to: to, subject: subject, text: text, cc: cc, bcc: bcc, reply_to: reply_to,
45
+ html: html, attachments: attachments, headers: headers }
46
+ id = idempotency_key.nil? ? nil : Mime.idempotent_id(idempotency_key, from)
47
+ raw, message_id = Mime.build(fields, date, id)
48
+ BuiltMessage.new(raw, message_id)
49
+ end
50
+
51
+ # The message builder: the same message Mailset builds for its own mail.
52
+ # Headers in CRLF lines; names and a subject that aren't plain ASCII as
53
+ # RFC 2047 words; a text and an HTML part, quoted-printable; files in base64
54
+ # around them.
55
+ #
56
+ # @api private
57
+ module Mime
58
+ CRLF = "\r\n"
59
+ LINE_LENGTH = 76
60
+ MAX_NAME_CHARS = 200
61
+ # UTF-8 bytes in one encoded word: 60 base64 characters, 72 with its markers, under RFC 2047's 75.
62
+ WORD_BYTES = 45
63
+ MAX_MESSAGE_BYTES = 20 * 1024 * 1024
64
+ MAX_IDEMPOTENCY_KEY = 255
65
+
66
+ # Headers Mailset writes itself. Setting one here would let a caller pose as someone.
67
+ RESERVED = %w[
68
+ from sender to cc bcc reply-to subject date message-id mime-version content-type
69
+ content-transfer-encoding return-path
70
+ ].freeze
71
+
72
+ # What a message takes.
73
+ FIELDS = %i[from to cc bcc reply_to subject text html attachments headers].freeze
74
+
75
+ # Control characters, and the marks that make text run the other way.
76
+ UNSAFE_IN_NAME = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/.freeze
77
+ SPACES = /[[:space:]\u{feff}]+/.freeze
78
+
79
+ # The endings a bare domain needs before it's taken for an address.
80
+ ENDINGS = %w[
81
+ com org net edu gov io co ai app dev pro sh me so to fm tv gg cc xyz info biz tech blog shop store site page
82
+ cloud email news studio design agency online eu us uk ca de fr es it nl br pt au jp in ch se no dk fi pl be
83
+ at ie nz mx ar
84
+ ].join('|')
85
+ REST = %q([^[:space:]<>"']*)
86
+ LABEL = '[a-z0-9](?:[a-z0-9-]*[a-z0-9])?'
87
+ # An email address, a full address, one starting www., or a bare domain with an ending we know.
88
+ FOUND = Regexp.new(
89
+ [
90
+ "[a-z0-9._%+-]+@(?:#{LABEL}\\.)+[a-z]{2,}",
91
+ "https?://#{REST}",
92
+ "www\\.#{REST}",
93
+ "(?:#{LABEL}\\.)+(?:#{ENDINGS})(?![a-z0-9-])(?:[/?#]#{REST})?"
94
+ ].join('|'),
95
+ Regexp::IGNORECASE
96
+ )
97
+
98
+ DAYS = %w[Sun Mon Tue Wed Thu Fri Sat].freeze
99
+ MONTHS = %w[Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec].freeze
100
+
101
+ module_function
102
+
103
+ def refused(message)
104
+ InvalidRequestError.new(message)
105
+ end
106
+
107
+ # Text as UTF-8, or refused.
108
+ def utf8(value, what)
109
+ text = value.to_s
110
+ text = text.dup.force_encoding(Encoding::UTF_8) if text.encoding == Encoding::BINARY
111
+ text = text.encode(Encoding::UTF_8)
112
+ raise refused("#{what} isn’t valid UTF-8.") unless text.valid_encoding?
113
+
114
+ text
115
+ rescue EncodingError
116
+ raise refused("#{what} isn’t valid UTF-8.")
117
+ end
118
+
119
+ def no_breaks(value, what)
120
+ text = utf8(value, what)
121
+ raise refused("#{what} can’t contain line breaks.") if text.match?(/[\r\n]/)
122
+
123
+ text
124
+ end
125
+
126
+ def plain?(text)
127
+ text.match?(/\A[\x20-\x7e]*\z/)
128
+ end
129
+
130
+ # One address: `ana@example.com`, `Ana <ana@example.com>`, or a Hash with `name:` and
131
+ # `email:`. Answers [name or nil, email].
132
+ def address(value)
133
+ case value
134
+ when Hash
135
+ name = value[:name] || value['name']
136
+ email = value[:email] || value['email']
137
+ raise refused('An address as a Hash needs email:.') unless email
138
+
139
+ [name.nil? || name.to_s.empty? ? nil : no_breaks(name, 'A name'), no_breaks(email, 'An address').strip]
140
+ when String
141
+ text = no_breaks(value, 'An address').strip
142
+ named = text.match(/\A(.*)<([^<>\s]+@[^<>\s]+)>\z/)
143
+ return [nil, text] unless named
144
+
145
+ name = named[1].strip.sub(/\A"(.*)"\z/, '\1')
146
+ [name.empty? ? nil : name, named[2]]
147
+ else
148
+ raise refused('An address is text, such as "Ana <ana@example.com>", or a Hash with name: and email:.')
149
+ end
150
+ end
151
+
152
+ def list(value)
153
+ return [] if value.nil?
154
+
155
+ (value.is_a?(Array) ? value : [value]).map { |one| address(one) }
156
+ end
157
+
158
+ # A name fit for a header: one line, no control characters, at most 200
159
+ # characters. Nil when nothing is left of it.
160
+ def header_name(name)
161
+ return nil if name.nil? || name.empty?
162
+
163
+ clean = name.gsub(UNSAFE_IN_NAME, ' ').gsub(SPACES, ' ').strip
164
+ clean = clean.each_char.first(MAX_NAME_CHARS).join.strip
165
+ clean.empty? ? nil : clean
166
+ end
167
+
168
+ # RFC 2047 encoded words for text: each under 75 characters, each holding
169
+ # whole characters, folded onto lines of their own.
170
+ def encoded_words(text)
171
+ words = []
172
+ word = +''
173
+ bytes = 0
174
+ text.each_char do |char|
175
+ size = char.bytesize
176
+ if !word.empty? && bytes + size > WORD_BYTES
177
+ words << word
178
+ word = +''
179
+ bytes = 0
180
+ end
181
+ word << char
182
+ bytes += size
183
+ end
184
+ words << word
185
+ words.map { |part| "=?UTF-8?B?#{Base64url.strict_encode(part)}?=" }.join("#{CRLF} ")
186
+ end
187
+
188
+ # One encoded word for text that isn't plain ASCII, as a file's name takes it.
189
+ def encode_words(text)
190
+ plain?(text) ? text : "=?UTF-8?B?#{Base64url.strict_encode(text)}?="
191
+ end
192
+
193
+ # One address with its name, as RFC 5322 writes it: `"Ana Souza" <ana@example.com>`.
194
+ def shown(name, email)
195
+ clean = header_name(name)
196
+ return email unless clean
197
+
198
+ phrase = plain?(clean) ? %("#{clean.gsub(/["\\]/) { |char| "\\#{char}" }}") : encoded_words(clean)
199
+ "#{phrase} <#{email}>"
200
+ end
201
+
202
+ # A To or Cc value, folded between addresses so a long list keeps to short lines.
203
+ def address_list(items)
204
+ value = +''
205
+ width = 4
206
+ items.each_with_index do |one, index|
207
+ item = index < items.length - 1 ? "#{one}," : one
208
+ lines = item.split(CRLF, -1)
209
+ if index.positive?
210
+ fold = width + 1 + lines[0].length > LINE_LENGTH
211
+ value << (fold ? "#{CRLF} " : ' ')
212
+ width = fold ? 1 : width + 1
213
+ end
214
+ value << item
215
+ width = lines.length > 1 ? lines[-1].length : width + item.length
216
+ end
217
+ value
218
+ end
219
+
220
+ # RFC 5322's date, in UTC.
221
+ def mail_date(time)
222
+ utc = time.to_time.getutc
223
+ format('%<day>s, %<date>d %<month>s %<year>d %<hour>02d:%<minute>02d:%<second>02d +0000',
224
+ day: DAYS[utc.wday], date: utc.day, month: MONTHS[utc.month - 1], year: utc.year,
225
+ hour: utc.hour, minute: utc.min, second: utc.sec)
226
+ end
227
+
228
+ # Quoted-printable (RFC 2045) for a text part: CRLF lines, none past 76
229
+ # characters, `=` at a line's end joining it to the next.
230
+ def quoted_printable(text)
231
+ bytes = text.gsub(/\r\n|\r|\n/, "\n").b.bytes
232
+ lines = []
233
+ line = +''
234
+ bytes.each_with_index do |byte, index|
235
+ if byte == 0x0a
236
+ lines << line
237
+ line = +''
238
+ next
239
+ end
240
+ at_line_end = index + 1 == bytes.length || bytes[index + 1] == 0x0a
241
+ literal = (byte >= 33 && byte <= 126 && byte != 61) || ([32, 9].include?(byte) && !at_line_end)
242
+ piece = literal ? byte.chr : format('=%02X', byte)
243
+ if line.length + piece.length > LINE_LENGTH - 1
244
+ lines << "#{line}="
245
+ line = +''
246
+ end
247
+ line << piece
248
+ end
249
+ lines << line
250
+ lines.join(CRLF)
251
+ end
252
+
253
+ # Bytes in base64, in CRLF lines of 76: 57 bytes a line.
254
+ def base64_lines(bytes)
255
+ [bytes].pack('m57').gsub("\n", CRLF).chomp(CRLF)
256
+ end
257
+
258
+ def escaped(text)
259
+ text.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;')
260
+ end
261
+
262
+ # The HTML twin of plain text: paragraphs and line breaks, and the
263
+ # addresses its writer wrote out (`https://…`, `www.…`) as links.
264
+ def html_of_text(text)
265
+ parts = text.split(/\n{2,}/, -1)
266
+ parts = [''] if parts.empty?
267
+ "<!doctype html><html><body>#{parts.map { |part| "<p>#{linked_html(part)}</p>" }.join}</body></html>"
268
+ end
269
+
270
+ def linked_html(text)
271
+ link_parts(text).map do |run, href|
272
+ href ? %(<a href="#{escaped(href)}">#{escaped(run)}</a>) : escaped(run).gsub("\n", '<br>')
273
+ end.join
274
+ end
275
+
276
+ # Text cut into runs, [text, href or nil], with what was written as a web
277
+ # address (`https://…`, `www.…`) marked to link. A bare domain stays text.
278
+ def link_parts(text)
279
+ parts = []
280
+ push = lambda do |run|
281
+ next if run.empty?
282
+
283
+ if parts.last && parts.last[1].nil?
284
+ parts.last[0] << run
285
+ else
286
+ parts << [+run, nil]
287
+ end
288
+ end
289
+ at = 0
290
+ text.to_enum(:scan, FOUND).map { Regexp.last_match }.each do |match|
291
+ start = match.begin(0)
292
+ whole = match[0]
293
+ before = start.positive? ? text[start - 1] : ''
294
+ written = trimmed(whole)
295
+ inside = before.match?(%r{[a-z0-9@/._-]}i)
296
+ email = written.include?('@') && !written.match?(%r{\Ahttps?://}i)
297
+ bare = !written.match?(%r{\A(?:https?://|www\.)}i)
298
+ push.call(text[at...start])
299
+ if inside || email || written.empty? || bare
300
+ push.call(whole)
301
+ else
302
+ href = written.match?(%r{\Ahttps?://}i) ? written : "https://#{written}"
303
+ if href.match?(%r{\Ahttps?://[^/?#\s]+}i)
304
+ parts << [written, href]
305
+ else
306
+ push.call(written)
307
+ end
308
+ push.call(whole[written.length..])
309
+ end
310
+ at = start + whole.length
311
+ end
312
+ push.call(text[at..] || '')
313
+ parts
314
+ end
315
+
316
+ # Punctuation that ends the sentence, not the address. A bracket stays when the address opened it.
317
+ def trimmed(written)
318
+ address = written
319
+ loop do
320
+ last = address[-1] || ''
321
+ if !last.empty? && ".,;:!?'\"".include?(last)
322
+ address = address[0...-1]
323
+ elsif last == ')' && !address.include?('(')
324
+ address = address[0...-1]
325
+ elsif last == ']' && !address.include?('[')
326
+ address = address[0...-1]
327
+ else
328
+ return address
329
+ end
330
+ end
331
+ end
332
+
333
+ # A name safe in a header's quotes; anything not plain as an encoded word.
334
+ def quoted_name(name)
335
+ clean = name.gsub(/[\r\n"\\]/, '_')
336
+ clean = 'attachment' if clean.empty?
337
+ %("#{plain?(clean) ? clean : encode_words(clean)}")
338
+ end
339
+
340
+ # One file: a Hash with `filename:`, `content_type:` and its bytes as
341
+ # `content:` (a String or an IO), `base64:` or `path:`. Answers [name, type, bytes].
342
+ def file(attachment)
343
+ unless attachment.is_a?(Hash)
344
+ raise refused('A file is a Hash with filename:, content_type: and content:, base64: or path:.')
345
+ end
346
+
347
+ given = attachment.transform_keys(&:to_sym)
348
+ unknown = given.keys - %i[filename content_type content base64 path]
349
+ raise ArgumentError, "An attachment has no #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
350
+
351
+ filename = given[:filename] || (given[:path] && File.basename(given[:path].to_s))
352
+ raise refused('A file needs a filename.') if filename.nil? || filename.to_s.empty?
353
+
354
+ [
355
+ no_breaks(filename, 'A file name'),
356
+ no_breaks(given[:content_type] || 'application/octet-stream', 'A content type'),
357
+ file_bytes(given, filename)
358
+ ]
359
+ end
360
+
361
+ def file_bytes(given, filename)
362
+ if given.key?(:base64)
363
+ bytes = Base64url.strict_decode(given[:base64].to_s.gsub(/\s+/, ''))
364
+ raise refused("#{filename} isn’t valid base64.") unless bytes
365
+
366
+ bytes
367
+ elsif given.key?(:content)
368
+ content = given[:content]
369
+ (content.respond_to?(:read) ? content.read : content.to_s).b
370
+ elsif given[:path]
371
+ File.binread(given[:path].to_s)
372
+ else
373
+ raise refused("#{filename} has no content:, base64: or path:.")
374
+ end
375
+ end
376
+
377
+ def file_part(boundary, name, type, bytes)
378
+ [
379
+ "--#{boundary}",
380
+ "Content-Type: #{type}; name=#{quoted_name(name)}",
381
+ 'Content-Transfer-Encoding: base64',
382
+ "Content-Disposition: attachment; filename=#{quoted_name(name)}",
383
+ '',
384
+ base64_lines(bytes)
385
+ ].join(CRLF)
386
+ end
387
+
388
+ # Bcc, Reply-To and the caller's own headers, after Mailset's.
389
+ def extra_headers(fields)
390
+ lines = []
391
+ bcc = list(fields[:bcc])
392
+ # Mailset reads Bcc to know who gets it, then takes it out of what's sent.
393
+ lines << "Bcc: #{bcc.map { |name, email| shown(name, email) }.join(', ')}" unless bcc.empty?
394
+ reply_to = list(fields[:reply_to])
395
+ lines << "Reply-To: #{reply_to.map { |name, email| shown(name, email) }.join(', ')}" unless reply_to.empty?
396
+ (fields[:headers] || {}).each do |name, value|
397
+ name = name.to_s
398
+ unless name.match?(/\A[A-Za-z0-9-]+\z/) && !RESERVED.include?(name.downcase)
399
+ raise refused("#{name} isn’t a header this can set.")
400
+ end
401
+
402
+ lines << "#{name}: #{no_breaks(value, name)}"
403
+ end
404
+ lines
405
+ end
406
+
407
+ # The Message-ID an idempotency key stands for: a hash of the key and the
408
+ # From address, at the From domain. The same key from the same address is
409
+ # the same send; the address is in the hash because two mailboxes of one
410
+ # domain may both call a send `welcome-1`.
411
+ def idempotent_id(key, from)
412
+ raise refused('idempotency_key is text, such as "receipt-8842".') unless key.is_a?(String)
413
+ raise refused('idempotency_key can’t be empty.') if key.strip.empty?
414
+ raise refused("idempotency_key is at most #{MAX_IDEMPOTENCY_KEY} characters.") if key.length > MAX_IDEMPOTENCY_KEY
415
+
416
+ no_breaks(key, 'idempotency_key')
417
+ email = address(from)[1].downcase
418
+ hash = OpenSSL::Digest::SHA256.digest("mailset-idempotency-v1\n#{email}\n#{key}")
419
+ "#{hash[0, 16].unpack1('H*')}@#{email.split('@')[1] || 'mailset.app'}"
420
+ end
421
+
422
+ # A message's fields as a Hash with symbol keys, or ArgumentError for one it doesn't take.
423
+ def fields_of(value, extra = [])
424
+ raise ArgumentError, 'A message is a Hash of its fields' unless value.is_a?(Hash)
425
+
426
+ given = value.transform_keys(&:to_sym)
427
+ unknown = given.keys - FIELDS - extra
428
+ raise ArgumentError, "A message has no #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
429
+
430
+ given
431
+ end
432
+
433
+ # The whole message, and its Message-ID: random at the From domain
434
+ # unless one is given.
435
+ def build(fields, date, id = nil)
436
+ %i[from to subject text].each do |name|
437
+ raise refused("A message needs #{name}:.") if fields[name].nil?
438
+ end
439
+ from_name, from_email = address(fields[:from])
440
+ message_id = id || "#{SecureRandom.hex(16)}@#{from_email.split('@')[1] || 'mailset.app'}"
441
+ boundary = "ms_#{SecureRandom.hex(12)}"
442
+ text = utf8(fields[:text], 'The text')
443
+ html = fields[:html].nil? ? html_of_text(text) : utf8(fields[:html], 'The HTML')
444
+ subject = no_breaks(fields[:subject], 'The subject')
445
+ files = (fields[:attachments] || []).map { |attachment| file(attachment) }
446
+ to = list(fields[:to]).map { |name, email| shown(name, email) }
447
+ cc = list(fields[:cc]).map { |name, email| shown(name, email) }
448
+ headers = [
449
+ "From: #{shown(from_name, from_email)}",
450
+ *(to.empty? ? [] : ["To: #{address_list(to)}"]),
451
+ *(cc.empty? ? [] : ["Cc: #{address_list(cc)}"]),
452
+ "Subject: #{plain?(subject) ? subject : encoded_words(subject)}",
453
+ "Date: #{mail_date(date)}",
454
+ "Message-ID: <#{message_id}>",
455
+ *extra_headers(fields),
456
+ 'MIME-Version: 1.0'
457
+ ]
458
+ [assemble(headers, boundary, text, html, files), message_id]
459
+ end
460
+
461
+ # A message for `campaigns.submit` and `sending.submit`: base64 of the
462
+ # whole message, built from its fields or given as `raw:`.
463
+ def base64_of(fields, now)
464
+ raw = fields[:raw]
465
+ unless raw.nil?
466
+ raise refused('raw: is the whole message, not its fields beside it.') if fields.key?(:from)
467
+
468
+ return Base64url.strict_encode(raw.respond_to?(:read) ? raw.read : raw.to_s)
469
+ end
470
+
471
+ message, = build(fields, Time.at(now / 1000r))
472
+ Base64url.strict_encode(message)
473
+ end
474
+
475
+ def assemble(headers, boundary, text, html, files)
476
+ part = lambda do |type, body|
477
+ [
478
+ "--#{boundary}", "Content-Type: #{type}; charset=UTF-8", 'Content-Transfer-Encoding: quoted-printable', '',
479
+ quoted_printable(body)
480
+ ].join(CRLF)
481
+ end
482
+ alternative = [part.call('text/plain', text), part.call('text/html', html), "--#{boundary}--", ''].join(CRLF)
483
+ if files.empty?
484
+ return [*headers, "Content-Type: multipart/alternative; boundary=\"#{boundary}\"", '', alternative].join(CRLF)
485
+ end
486
+
487
+ # Parsers find a delimiter by its start, so neither boundary may begin with the other.
488
+ mixed = "mixed_#{boundary}"
489
+ [
490
+ *headers, "Content-Type: multipart/mixed; boundary=\"#{mixed}\"", '', "--#{mixed}",
491
+ "Content-Type: multipart/alternative; boundary=\"#{boundary}\"", '', alternative,
492
+ *files.map { |name, type, bytes| file_part(mixed, name, type, bytes) },
493
+ "--#{mixed}--", ''
494
+ ].join(CRLF)
495
+ end
496
+ end
497
+ end