@hamur/mail 0.0.0-stage → 0.0.2

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 (90) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/devtools.js +268 -0
  4. package/dist/src/index.js +573 -0
  5. package/dist/src/server/index.js +916 -0
  6. package/dist/src/test.js +39 -0
  7. package/dist/types/src/address.d.ts +14 -0
  8. package/dist/types/src/build/devtools.d.ts +20 -0
  9. package/dist/types/src/build/outbox.d.ts +35 -0
  10. package/dist/types/src/build/setup.d.ts +22 -0
  11. package/dist/types/src/build/templates.d.ts +12 -0
  12. package/dist/types/src/devtools-model.d.ts +12 -0
  13. package/dist/types/src/devtools.d.ts +2 -0
  14. package/dist/types/src/html.d.ts +10 -0
  15. package/dist/types/src/index.d.ts +24 -0
  16. package/dist/types/src/mime.d.ts +32 -0
  17. package/dist/types/src/module.d.ts +3 -0
  18. package/dist/types/src/options.d.ts +12 -0
  19. package/dist/types/src/server/deliver.d.ts +15 -0
  20. package/dist/types/src/server/devtools-routes.d.ts +1 -0
  21. package/dist/types/src/server/door-dev.d.ts +3 -0
  22. package/dist/types/src/server/door.d.ts +2 -0
  23. package/dist/types/src/server/hooks.d.ts +5 -0
  24. package/dist/types/src/server/index.d.ts +6 -0
  25. package/dist/types/src/server/message.d.ts +3 -0
  26. package/dist/types/src/server/plugin.d.ts +1 -0
  27. package/dist/types/src/server/preview.d.ts +8 -0
  28. package/dist/types/src/server/queue.d.ts +19 -0
  29. package/dist/types/src/server/runtime.d.ts +5 -0
  30. package/dist/types/src/server/send.d.ts +54 -0
  31. package/dist/types/src/server/task.d.ts +4 -0
  32. package/dist/types/src/server/template.d.ts +8 -0
  33. package/dist/types/src/smtp/client.d.ts +28 -0
  34. package/dist/types/src/smtp/dkim.d.ts +8 -0
  35. package/dist/types/src/smtp/sockets.d.ts +42 -0
  36. package/dist/types/src/test.d.ts +27 -0
  37. package/dist/types/src/transport.d.ts +28 -0
  38. package/dist/types/src/transports/cloudflare.d.ts +17 -0
  39. package/dist/types/src/transports/http.d.ts +26 -0
  40. package/dist/types/src/transports/mailgun.d.ts +9 -0
  41. package/dist/types/src/transports/outbox.d.ts +9 -0
  42. package/dist/types/src/transports/postmark.d.ts +8 -0
  43. package/dist/types/src/transports/resend.d.ts +7 -0
  44. package/dist/types/src/transports/sendgrid.d.ts +7 -0
  45. package/dist/types/src/transports/ses.d.ts +9 -0
  46. package/dist/types/src/transports/smtp.d.ts +3 -0
  47. package/dist/types/src/types.d.ts +124 -0
  48. package/package.json +48 -4
  49. package/src/address.ts +86 -0
  50. package/src/build/devtools.ts +81 -0
  51. package/src/build/outbox.ts +69 -0
  52. package/src/build/setup.ts +226 -0
  53. package/src/build/templates.ts +113 -0
  54. package/src/devtools-model.ts +24 -0
  55. package/src/devtools.ts +351 -0
  56. package/src/env.d.ts +36 -0
  57. package/src/html.ts +274 -0
  58. package/src/index.ts +25 -0
  59. package/src/mime.ts +220 -0
  60. package/src/module.ts +11 -0
  61. package/src/options.ts +157 -0
  62. package/src/server/deliver.ts +54 -0
  63. package/src/server/devtools-routes.ts +32 -0
  64. package/src/server/door-dev.ts +6 -0
  65. package/src/server/door.ts +4 -0
  66. package/src/server/hooks.ts +13 -0
  67. package/src/server/index.ts +28 -0
  68. package/src/server/message.ts +36 -0
  69. package/src/server/plugin.ts +4 -0
  70. package/src/server/preview.ts +41 -0
  71. package/src/server/queue.ts +58 -0
  72. package/src/server/runtime.ts +45 -0
  73. package/src/server/send.ts +308 -0
  74. package/src/server/task.ts +13 -0
  75. package/src/server/template.ts +37 -0
  76. package/src/smtp/client.ts +305 -0
  77. package/src/smtp/dkim.ts +72 -0
  78. package/src/smtp/sockets.ts +296 -0
  79. package/src/test.ts +70 -0
  80. package/src/transport.ts +35 -0
  81. package/src/transports/cloudflare.ts +68 -0
  82. package/src/transports/http.ts +75 -0
  83. package/src/transports/mailgun.ts +31 -0
  84. package/src/transports/outbox.ts +64 -0
  85. package/src/transports/postmark.ts +59 -0
  86. package/src/transports/resend.ts +46 -0
  87. package/src/transports/sendgrid.ts +64 -0
  88. package/src/transports/ses.ts +53 -0
  89. package/src/transports/smtp.ts +37 -0
  90. package/src/types.ts +104 -0
@@ -0,0 +1,37 @@
1
+ import { createAppContext, createHead, createState, type AdapterServerEntry, type ResolvedRoute } from "hamur/adapter"
2
+ import { mailHtml, type MailSite } from "../html.ts"
3
+
4
+ export interface TemplateSite extends MailSite {
5
+ /** The document's language: `i18n.defaultLocale`, else `en`. */
6
+ lang: string
7
+ }
8
+
9
+ /** `component` rendered by the adapter as a root of its own, outside any request, in the mail's document. */
10
+ export async function renderTemplate(
11
+ renderComponent: NonNullable<AdapterServerEntry["renderComponent"]>,
12
+ component: unknown,
13
+ props: Record<string, unknown>,
14
+ site: TemplateSite,
15
+ ): Promise<string> {
16
+ const { baseURL } = site
17
+ const route = {
18
+ name: "mail",
19
+ path: "/",
20
+ fullPath: "/",
21
+ params: {},
22
+ query: {},
23
+ search: {},
24
+ hash: "",
25
+ meta: {},
26
+ matched: [],
27
+ } as ResolvedRoute
28
+ const app = createAppContext({ state: createState(), config: { public: {} }, head: createHead({ baseURL }) })
29
+ const { html } = await renderComponent(component, props, {
30
+ app,
31
+ url: new URL(baseURL, site.origin),
32
+ route,
33
+ baseURL,
34
+ idPrefix: "mail",
35
+ })
36
+ return `<!doctype html><html lang="${site.lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head><body>${mailHtml(html, site)}</body></html>`
37
+ }
@@ -0,0 +1,305 @@
1
+ import { needsSmtpUtf8 } from "../address.ts"
2
+ import { UnconfirmedError, type MailSender, type OutgoingMail } from "../transport.ts"
3
+ import type { SmtpConnect, SmtpSocket } from "./sockets.ts"
4
+
5
+ export interface SmtpOptions {
6
+ host: string
7
+ port: number
8
+ secure: "tls" | "starttls" | false
9
+ /** Read at each connection; undefined sends no AUTH. */
10
+ credentials?: () => { user: string; password: string }
11
+ /** Keeps one connection open between sends; false opens and closes one per send. */
12
+ reuse: boolean
13
+ }
14
+
15
+ /** In milliseconds. */
16
+ export interface SmtpTimes {
17
+ connect: number
18
+ command: number
19
+ idle: number
20
+ }
21
+
22
+ const TIMES: SmtpTimes = { connect: 10_000, command: 30_000, idle: 30_000 }
23
+ const CONTROL = /[\x00-\x1f\x7f]/
24
+ const CONTROLS = /[\x00-\x1f\x7f]+/g
25
+ const HOST_NAME = /^[A-Za-z0-9.-]+$/
26
+ const REPLY = /^([2-5]\d\d)(?:([ -])([^]*))?$/
27
+ const MAX_REPLY = 65_536
28
+ const MAX_ERROR = 500
29
+ const BODY_CHUNK = 65_536
30
+ /** The failure after the message was sent in full: no refusal, so sending again may deliver it twice. */
31
+ export const UNCONFIRMED = "the server did not confirm the message and may have accepted it"
32
+ const encoder = new TextEncoder()
33
+
34
+ interface Reply {
35
+ code: number
36
+ lines: string[]
37
+ }
38
+
39
+ const seconds = (ms: number): string => `${ms / 1000} s`
40
+
41
+ function base64(text: string): string {
42
+ let binary = ""
43
+ for (const byte of encoder.encode(text)) binary += String.fromCharCode(byte)
44
+ return btoa(binary)
45
+ }
46
+
47
+ /** The message as the server reads it: every line end a CRLF, the last line's included. */
48
+ export function messageText(raw: string): string {
49
+ const text = raw.replace(/\r\n|\r|\n/g, "\r\n")
50
+ return text.endsWith("\r\n") ? text : `${text}\r\n`
51
+ }
52
+
53
+ /** RFC 5321 §4.5.2, and the line that ends the message. */
54
+ export function dataOf(raw: string): string {
55
+ return `${messageText(raw).replace(/(^|\n)\./g, "$1..")}.\r\n`
56
+ }
57
+
58
+ class SmtpConnection {
59
+ #socket: SmtpSocket
60
+ #timeout: number
61
+ #decoder = new TextDecoder()
62
+ #text = ""
63
+ #extensions = new Map<string, string[]>()
64
+ #secrets: string[] = []
65
+ #addresses: string[] = []
66
+
67
+ constructor(socket: SmtpSocket, timeout: number) {
68
+ this.#socket = socket
69
+ this.#timeout = timeout
70
+ }
71
+
72
+ async open(options: SmtpOptions, name: string): Promise<void> {
73
+ if (options.secure === "tls") await this.#startTls()
74
+ this.#expect(2, await this.#within("the greeting", () => this.#reply()))
75
+ await this.#hello(name)
76
+ if (options.secure === "starttls") {
77
+ if (!this.#extensions.has("STARTTLS"))
78
+ throw new Error(
79
+ `${options.host}:${options.port} did not offer STARTTLS; refusing to send credentials in clear text`,
80
+ )
81
+ await this.#command("STARTTLS", "STARTTLS")
82
+ await this.#startTls()
83
+ await this.#hello(name)
84
+ }
85
+ if (options.credentials) await this.#login(options.credentials())
86
+ }
87
+
88
+ /** True when a kept connection holds no bytes of before and the server still answers on it. */
89
+ async reset(): Promise<boolean> {
90
+ this.#socket.hold?.(true)
91
+ try {
92
+ if (this.#text !== "" || this.#socket.stale?.()) throw new Error("bytes arrived while the connection was idle")
93
+ await this.#command("RSET", "RSET")
94
+ return true
95
+ } catch {
96
+ this.close()
97
+ return false
98
+ }
99
+ }
100
+
101
+ async deliver(mail: OutgoingMail): Promise<void> {
102
+ const { from, to, cc, bcc, replyTo } = mail.message
103
+ const international = [from, ...to, ...cc, ...bcc, ...(replyTo ? [replyTo] : [])].find(needsSmtpUtf8)
104
+ if (international && !this.#extensions.has("SMTPUTF8"))
105
+ throw new Error(`the server does not offer SMTPUTF8, needed for ${JSON.stringify(international.address)}`)
106
+ this.#addresses = [mail.envelope.from, ...mail.envelope.to]
107
+ await this.#command("MAIL", `MAIL FROM:<${mail.envelope.from}>${international ? " SMTPUTF8" : ""}`)
108
+ for (const address of mail.envelope.to) await this.#command("RCPT", `RCPT TO:<${address}>`)
109
+ await this.#command("DATA", "DATA", 3)
110
+ const bytes = encoder.encode(dataOf(mail.raw))
111
+ const write = (from: number, to?: number) =>
112
+ this.#within("the message", () => this.#socket.write(bytes.subarray(from, to)))
113
+ let at = 0
114
+ for (; at + BODY_CHUNK < bytes.length; at += BODY_CHUNK) await write(at, at + BODY_CHUNK)
115
+ this.#expect(2, await this.#confirm(() => write(at)))
116
+ }
117
+
118
+ /** Sends the end of the message; from there on, a lost connection leaves open whether the server accepted it. */
119
+ async #confirm(finish: () => Promise<void>): Promise<Reply> {
120
+ try {
121
+ await finish()
122
+ return await this.#within("the message", () => this.#reply())
123
+ } catch (cause) {
124
+ throw new UnconfirmedError(UNCONFIRMED, { cause })
125
+ }
126
+ }
127
+
128
+ /** Leaves the connection open without keeping the process running. */
129
+ rest(): void {
130
+ this.#socket.hold?.(false)
131
+ }
132
+
133
+ async quit(): Promise<void> {
134
+ try {
135
+ await this.#within("QUIT", () => this.#socket.write(encoder.encode("QUIT\r\n")))
136
+ this.#socket.end()
137
+ } catch {
138
+ this.close()
139
+ }
140
+ }
141
+
142
+ close(): void {
143
+ this.#socket.close()
144
+ }
145
+
146
+ async #startTls(): Promise<void> {
147
+ this.#socket = await this.#within("the TLS handshake", () => this.#socket.startTls())
148
+ // What arrived before the handshake was not protected by it (RFC 3207 §4.2).
149
+ this.#text = ""
150
+ this.#decoder = new TextDecoder()
151
+ this.#extensions.clear()
152
+ }
153
+
154
+ async #hello(name: string): Promise<void> {
155
+ const { lines } = await this.#command("EHLO", `EHLO ${name}`)
156
+ this.#extensions = new Map(
157
+ lines.slice(1).map((line) => {
158
+ const [keyword = "", ...values] = line.trim().toUpperCase().split(/\s+/)
159
+ return [keyword, values]
160
+ }),
161
+ )
162
+ }
163
+
164
+ async #login({ user, password }: { user: string; password: string }): Promise<void> {
165
+ const plain = base64(`\0${user}\0${password}`)
166
+ this.#secrets = [user, password, plain, base64(user), base64(password)]
167
+ const mechanisms = this.#extensions.get("AUTH") ?? []
168
+ if (mechanisms.includes("PLAIN")) {
169
+ await this.#command("AUTH", `AUTH PLAIN ${plain}`)
170
+ } else if (mechanisms.includes("LOGIN")) {
171
+ await this.#command("AUTH", "AUTH LOGIN", 3)
172
+ await this.#command("AUTH", base64(user), 3)
173
+ await this.#command("AUTH", base64(password))
174
+ } else throw new Error("the server offers neither AUTH PLAIN nor AUTH LOGIN")
175
+ }
176
+
177
+ /** `verb` names the command in a timeout; `line` may hold a secret and never reaches an error. */
178
+ async #command(verb: string, line: string, expected: 2 | 3 = 2): Promise<Reply> {
179
+ if (CONTROL.test(line)) throw new Error(`the ${verb} command holds a line break`)
180
+ const reply = await this.#within(verb, async () => {
181
+ await this.#socket.write(encoder.encode(`${line}\r\n`))
182
+ return this.#reply()
183
+ })
184
+ return this.#expect(expected, reply)
185
+ }
186
+
187
+ #expect(expected: 2 | 3, reply: Reply): Reply {
188
+ if (Math.floor(reply.code / 100) === expected) return reply
189
+ throw new Error(`${reply.code} ${this.#shown(reply.lines.join(" "))}`.trim())
190
+ }
191
+
192
+ /** The server's text, without the credentials and addresses a server repeats in it. */
193
+ #shown(text: string): string {
194
+ const hidden = [...this.#secrets, ...this.#addresses].filter(Boolean).sort((a, b) => b.length - a.length)
195
+ let shown = text
196
+ if (hidden.length) {
197
+ const any = hidden.map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")
198
+ shown = shown.replace(new RegExp(any, "gi"), "…")
199
+ }
200
+ return shown.replace(CONTROLS, " ").slice(0, MAX_ERROR)
201
+ }
202
+
203
+ async #reply(): Promise<Reply> {
204
+ const lines: string[] = []
205
+ let size = 0
206
+ while (true) {
207
+ const line = await this.#line()
208
+ const match = REPLY.exec(line)
209
+ size += line.length
210
+ if (!match || size > MAX_REPLY) throw new Error("the server sent something that is not an SMTP reply")
211
+ lines.push(match[3] ?? "")
212
+ if (match[2] !== "-") return { code: Number(match[1]), lines }
213
+ }
214
+ }
215
+
216
+ async #line(): Promise<string> {
217
+ while (true) {
218
+ const end = this.#text.indexOf("\n")
219
+ if (end >= 0) {
220
+ const line = this.#text.slice(0, end).replace(/\r$/, "")
221
+ this.#text = this.#text.slice(end + 1)
222
+ return line
223
+ }
224
+ if (this.#text.length > MAX_REPLY) throw new Error("the server sent something that is not an SMTP reply")
225
+ const chunk = await this.#socket.read()
226
+ if (!chunk) throw new Error("the server closed the connection")
227
+ this.#text += this.#decoder.decode(chunk, { stream: true })
228
+ }
229
+ }
230
+
231
+ async #within<T>(what: string, work: () => Promise<T>): Promise<T> {
232
+ let timer: ReturnType<typeof setTimeout> | undefined
233
+ const late = new Promise<never>((_, reject) => {
234
+ timer = setTimeout(() => {
235
+ reject(new Error(`the server did not answer ${what} within ${seconds(this.#timeout)}`))
236
+ this.close()
237
+ }, this.#timeout)
238
+ })
239
+ try {
240
+ return await Promise.race([work(), late])
241
+ } finally {
242
+ clearTimeout(timer)
243
+ }
244
+ }
245
+ }
246
+
247
+ async function connectWithin(options: SmtpOptions, connect: SmtpConnect, ms: number): Promise<SmtpSocket> {
248
+ const { host, port } = options
249
+ const abort = new AbortController()
250
+ let timer: ReturnType<typeof setTimeout> | undefined
251
+ const late = new Promise<never>((_, reject) => {
252
+ timer = setTimeout(() => {
253
+ reject(new Error(`${host}:${port} did not accept a connection within ${seconds(ms)}`))
254
+ abort.abort()
255
+ }, ms)
256
+ })
257
+ try {
258
+ return await Promise.race([connect({ host, port }, abort.signal), late])
259
+ } finally {
260
+ clearTimeout(timer)
261
+ }
262
+ }
263
+
264
+ /** One SMTP transaction per message; with `reuse` one idle connection is kept, and a send that finds none opens its own. */
265
+ export function createSmtp(options: SmtpOptions, connect: SmtpConnect, times: SmtpTimes = TIMES): MailSender {
266
+ let idle: { connection: SmtpConnection; timer: ReturnType<typeof setTimeout> } | undefined
267
+
268
+ const take = async (mail: OutgoingMail): Promise<SmtpConnection> => {
269
+ const kept = idle
270
+ idle = undefined
271
+ if (kept) {
272
+ clearTimeout(kept.timer)
273
+ if (await kept.connection.reset()) return kept.connection
274
+ }
275
+ const connection = new SmtpConnection(await connectWithin(options, connect, times.connect), times.command)
276
+ const host = mail.id.slice(mail.id.lastIndexOf("@") + 1)
277
+ try {
278
+ await connection.open(options, HOST_NAME.test(host) ? host : "[127.0.0.1]")
279
+ return connection
280
+ } catch (error) {
281
+ connection.close()
282
+ throw error
283
+ }
284
+ }
285
+
286
+ return {
287
+ async send(mail) {
288
+ const connection = await take(mail)
289
+ try {
290
+ await connection.deliver(mail)
291
+ } catch (error) {
292
+ connection.close()
293
+ throw error
294
+ }
295
+ if (!options.reuse || idle) return connection.quit()
296
+ const timer = setTimeout(() => {
297
+ idle = undefined
298
+ void connection.quit()
299
+ }, times.idle)
300
+ timer.unref()
301
+ connection.rest()
302
+ idle = { connection, timer }
303
+ },
304
+ }
305
+ }
@@ -0,0 +1,72 @@
1
+ import { base64Lines } from "../mime.ts"
2
+ import { messageText } from "./client.ts"
3
+
4
+ const SIGNED = ["from", "to", "subject", "date", "message-id", "mime-version", "content-type"]
5
+ const PEM = /^\s*-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/
6
+ const ALGORITHM = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }
7
+ const encoder = new TextEncoder()
8
+
9
+ export interface DkimOptions {
10
+ domain: string
11
+ selector: string
12
+ /** PKCS #8 PEM; its line breaks may be written `\n`, as in an env value of one line. */
13
+ privateKey: string
14
+ }
15
+
16
+ async function importKey(pem: string): Promise<CryptoKey> {
17
+ try {
18
+ const der = Uint8Array.from(atob(PEM.exec(pem.replace(/\\n/g, "\n"))![1]!.replace(/\s+/g, "")), (char) =>
19
+ char.charCodeAt(0),
20
+ )
21
+ return await crypto.subtle.importKey("pkcs8", der, ALGORITHM, false, ["sign"])
22
+ } catch {
23
+ throw new Error("mail.dkim.privateKey must be a PKCS #8 RSA private key in PEM")
24
+ }
25
+ }
26
+
27
+ /** RFC 6376 §3.4.2, without the line end. */
28
+ function relaxedHeader(field: string): string {
29
+ const colon = field.indexOf(":")
30
+ const value = field
31
+ .slice(colon + 1)
32
+ .replace(/\r\n/g, "")
33
+ .replace(/[ \t]+/g, " ")
34
+ .replace(/^ | $/g, "")
35
+ return `${field.slice(0, colon).toLowerCase()}:${value}`
36
+ }
37
+
38
+ /** RFC 6376 §3.4.4. */
39
+ function relaxedBody(body: string): string {
40
+ const text = body.replace(/[ \t]+/g, " ").replace(/ \r\n/g, "\r\n")
41
+ let end = text.length
42
+ while (text.endsWith("\r\n", end)) end -= 2
43
+ return end === 0 ? "" : `${text.slice(0, end)}\r\n`
44
+ }
45
+
46
+ /** The message with its `DKIM-Signature` header (RFC 6376) first, every line end a CRLF as the SMTP client sends it. */
47
+ export async function signDkim(raw: string, options: DkimOptions): Promise<string> {
48
+ const key = await importKey(options.privateKey)
49
+ const text = messageText(raw)
50
+ const split = text.indexOf("\r\n\r\n")
51
+ const fields = text.slice(0, split).split(/\r\n(?![ \t])/)
52
+ const bodyHash = await crypto.subtle.digest("SHA-256", encoder.encode(relaxedBody(text.slice(split + 4))))
53
+ const unsigned = [
54
+ "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;",
55
+ `d=${options.domain};`,
56
+ `s=${options.selector}; t=${Math.floor(Date.now() / 1000)};`,
57
+ `h=${SIGNED.join(":")};`,
58
+ `bh=${base64Lines(new Uint8Array(bodyHash))};`,
59
+ "b=",
60
+ ].join("\r\n ")
61
+ const signed = SIGNED.flatMap((name) => {
62
+ const field = fields.find((item) => item.toLowerCase().startsWith(`${name}:`))
63
+ return field === undefined ? [] : [`${relaxedHeader(field)}\r\n`]
64
+ })
65
+ const signature = await crypto.subtle.sign(
66
+ ALGORITHM,
67
+ key,
68
+ encoder.encode(`${signed.join("")}${relaxedHeader(unsigned)}`),
69
+ )
70
+ const value = base64Lines(new Uint8Array(signature)).replaceAll("\r\n", "\r\n ")
71
+ return `${unsigned}\r\n ${value}\r\n${text}`
72
+ }