@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,296 @@
1
+ import type { Socket } from "node:net"
2
+
3
+ /** One SMTP connection of a runtime, plain or over TLS. */
4
+ export interface SmtpSocket {
5
+ /** The next bytes; undefined once the server ended the connection. */
6
+ read(): Promise<Uint8Array | undefined>
7
+ write(bytes: Uint8Array<ArrayBuffer>): Promise<void>
8
+ /** The TLS socket over this connection, its certificate checked; bytes this socket still holds never reach it. */
9
+ startTls(): Promise<SmtpSocket>
10
+ /** Tears the connection down at once, whatever the server does. */
11
+ close(): void
12
+ /** Closes after the bytes written so far have left. */
13
+ end(): void
14
+ /** Whether bytes nobody asked for wait here, or the connection ended; absent where no connection is reused. */
15
+ stale?(): boolean
16
+ /** Whether the connection keeps the process running; absent where no connection outlives a send. */
17
+ hold?(held: boolean): void
18
+ }
19
+
20
+ export type SmtpConnect = (target: { host: string; port: number }, signal: AbortSignal) => Promise<SmtpSocket>
21
+
22
+ /** More than any reply: a server that sends this much unread is cut off. */
23
+ const MAX_UNREAD = 65_536
24
+ /** How long a server may keep its side open after QUIT, in milliseconds. */
25
+ const QUIT_GRACE = 1000
26
+ const LOST_IN_HANDSHAKE = "the connection closed during the TLS handshake"
27
+
28
+ /** The bytes of a socket until they are read; `cutOff` closes it when more than `MAX_UNREAD` wait. */
29
+ function createInbox(cutOff: () => void) {
30
+ const chunks: Uint8Array[] = []
31
+ let unread = 0
32
+ let ended = false
33
+ let failure: Error | undefined
34
+ let wake: (() => void) | undefined
35
+ return {
36
+ push(chunk: Uint8Array) {
37
+ if (ended) return
38
+ unread += chunk.length
39
+ if (unread > MAX_UNREAD) {
40
+ chunks.length = 0
41
+ ended = true
42
+ failure = new Error("the server sent more than an SMTP reply")
43
+ cutOff()
44
+ } else chunks.push(chunk)
45
+ wake?.()
46
+ },
47
+ end(error?: Error) {
48
+ ended = true
49
+ failure ??= error
50
+ wake?.()
51
+ },
52
+ async read(): Promise<Uint8Array | undefined> {
53
+ while (!chunks.length && !ended) await new Promise<void>((resolve) => (wake = resolve))
54
+ const chunk = chunks.shift()
55
+ if (!chunk && failure) throw failure
56
+ unread -= chunk?.length ?? 0
57
+ return chunk
58
+ },
59
+ stale: () => ended || chunks.length > 0,
60
+ }
61
+ }
62
+
63
+ /** `node:net` and `node:tls`, imported at first use so a Workers bundle never loads them. */
64
+ async function nodeModules() {
65
+ const netSpecifier = "node:net"
66
+ const tlsSpecifier = "node:tls"
67
+ const [net, tls] = await Promise.all([import(netSpecifier), import(tlsSpecifier)])
68
+ return { net: net as typeof import("node:net"), tls: tls as typeof import("node:tls") }
69
+ }
70
+
71
+ type NodeModules = Awaited<ReturnType<typeof nodeModules>>
72
+
73
+ function nodeSocket(socket: Socket, host: string, modules: NodeModules): SmtpSocket {
74
+ const inbox = createInbox(() => socket.destroy())
75
+ const onData = (chunk: Uint8Array) => inbox.push(chunk)
76
+ socket.on("data", onData)
77
+ socket.on("error", (error) => inbox.end(error))
78
+ socket.on("end", () => inbox.end())
79
+ socket.on("close", () => inbox.end())
80
+ return {
81
+ read: inbox.read,
82
+ write: (bytes) =>
83
+ new Promise((resolve, reject) => {
84
+ socket.write(bytes, (error) => (error ? reject(error) : resolve()))
85
+ }),
86
+ startTls: () =>
87
+ new Promise((resolve, reject) => {
88
+ socket.off("data", onData)
89
+ const secure = modules.tls.connect({
90
+ socket,
91
+ host,
92
+ rejectUnauthorized: true,
93
+ ...(modules.net.isIP(host) ? {} : { servername: host }),
94
+ })
95
+ secure.on("error", reject)
96
+ secure.once("close", () => reject(new Error(LOST_IN_HANDSHAKE)))
97
+ secure.once("secureConnect", () => resolve(nodeSocket(secure, host, modules)))
98
+ }),
99
+ close: () => void socket.destroy(),
100
+ // A write resolves once the kernel has its bytes, which it sends after destroy too.
101
+ end: () => void socket.destroy(),
102
+ stale: inbox.stale,
103
+ hold: (held) => void (held ? socket.ref() : socket.unref()),
104
+ }
105
+ }
106
+
107
+ export const nodeConnect: SmtpConnect = async ({ host, port }, signal) => {
108
+ const modules = await nodeModules()
109
+ return new Promise((resolve, reject) => {
110
+ const socket = modules.net.connect({ host, port })
111
+ signal.addEventListener("abort", () => socket.destroy(), { once: true })
112
+ socket.once("error", reject)
113
+ socket.once("connect", () => {
114
+ socket.setNoDelay(true)
115
+ resolve(nodeSocket(socket, host, modules))
116
+ })
117
+ })
118
+ }
119
+
120
+ /** The handlers of one `Bun.Socket` and the `SmtpSocket` over it; after `startTls` the plain handlers see ciphertext, which they drop. */
121
+ function bunEnd(host: string, modules: NodeModules) {
122
+ const inbox = createInbox(() => closing?.terminate())
123
+ let socket: Bun.Socket<undefined> | undefined
124
+ let closing: Bun.Socket<undefined> | undefined
125
+ let upgraded = false
126
+ let pending: { bytes: Uint8Array<ArrayBuffer>; resolve: () => void; reject: (error: Error) => void } | undefined
127
+
128
+ const fail = (error = new Error("the connection is closed")) => {
129
+ pending?.reject(error)
130
+ pending = undefined
131
+ }
132
+ const flush = () => {
133
+ const writing = pending
134
+ if (!writing || !socket) return
135
+ const sent = socket.write(writing.bytes)
136
+ if (sent < 0) return fail()
137
+ writing.bytes = writing.bytes.subarray(sent)
138
+ if (writing.bytes.length) return
139
+ pending = undefined
140
+ writing.resolve()
141
+ }
142
+ const handlers = {
143
+ data(_: Bun.Socket<undefined>, chunk: Uint8Array) {
144
+ if (!upgraded) inbox.push(chunk)
145
+ },
146
+ drain: flush,
147
+ end: () => inbox.end(),
148
+ error(_: Bun.Socket<undefined>, error: Error) {
149
+ inbox.end(error)
150
+ fail(error)
151
+ },
152
+ close(_: Bun.Socket<undefined>, error?: Error) {
153
+ inbox.end(error)
154
+ fail(error)
155
+ },
156
+ }
157
+ const attach = (opened: Bun.Socket<undefined>): SmtpSocket => {
158
+ socket = closing = opened
159
+ return {
160
+ read: inbox.read,
161
+ write: (bytes) =>
162
+ new Promise((resolve, reject) => {
163
+ pending = { bytes, resolve, reject }
164
+ flush()
165
+ }),
166
+ startTls: () =>
167
+ new Promise((resolve, reject) => {
168
+ upgraded = true
169
+ const next = bunEnd(host, modules)
170
+ const [raw, secure] = opened.upgradeTLS<undefined>({
171
+ tls: {
172
+ requestCert: true,
173
+ rejectUnauthorized: true,
174
+ ...(modules.net.isIP(host) ? {} : { serverName: host }),
175
+ },
176
+ socket: {
177
+ ...next.handlers,
178
+ close(closed, error) {
179
+ next.handlers.close(closed, error)
180
+ reject(error ?? new Error(LOST_IN_HANDSHAKE))
181
+ },
182
+ // Bun leaves the host name of the certificate to the handler.
183
+ handshake(shaken, success, error) {
184
+ const problem = success
185
+ ? (error ?? modules.tls.checkServerIdentity(host, shaken.getPeerCertificate()))
186
+ : (error ?? new Error("the TLS handshake failed"))
187
+ if (problem) {
188
+ reject(problem)
189
+ shaken.terminate()
190
+ } else resolve(next.attach(shaken))
191
+ },
192
+ },
193
+ })
194
+ closing = secure
195
+ raw.unref()
196
+ secure.ref()
197
+ }),
198
+ close: () => void closing?.terminate(),
199
+ end() {
200
+ opened.end()
201
+ opened.unref()
202
+ setTimeout(() => opened.terminate(), QUIT_GRACE).unref()
203
+ },
204
+ stale: inbox.stale,
205
+ hold: (held) => void (held ? opened.ref() : opened.unref()),
206
+ }
207
+ }
208
+ return { handlers, attach }
209
+ }
210
+
211
+ export const bunConnect: SmtpConnect = async ({ host, port }, signal) => {
212
+ const end = bunEnd(host, await nodeModules())
213
+ const socket = await Bun.connect<undefined>({ hostname: host, port, socket: end.handlers })
214
+ if (signal.aborted) {
215
+ socket.terminate()
216
+ throw signal.reason
217
+ }
218
+ return end.attach(socket)
219
+ }
220
+
221
+ interface WorkersSocket {
222
+ readable: ReadableStream<Uint8Array>
223
+ writable: WritableStream<Uint8Array>
224
+ opened: Promise<unknown>
225
+ closed: Promise<void>
226
+ close(): Promise<void>
227
+ startTls(): WorkersSocket
228
+ }
229
+
230
+ /** `connect` of `cloudflare:sockets`. */
231
+ export type WorkersConnect = (
232
+ address: { hostname: string; port: number },
233
+ options: { secureTransport: "starttls"; allowHalfOpen: boolean },
234
+ ) => WorkersSocket
235
+
236
+ function workersSocket(socket: WorkersSocket): SmtpSocket {
237
+ socket.opened.catch(() => {})
238
+ socket.closed.catch(() => {})
239
+ let reading: ReadableStreamDefaultReader<Uint8Array> | undefined
240
+ let writing: WritableStreamDefaultWriter<Uint8Array> | undefined
241
+ const end = () => void socket.close().catch(() => {})
242
+ return {
243
+ // Each call takes and releases the lock: startTls refuses locked streams.
244
+ async read() {
245
+ const reader = (reading = socket.readable.getReader())
246
+ try {
247
+ return (await reader.read()).value
248
+ } finally {
249
+ reader.releaseLock()
250
+ reading = undefined
251
+ }
252
+ },
253
+ async write(bytes) {
254
+ const writer = (writing = socket.writable.getWriter())
255
+ try {
256
+ await writer.write(bytes)
257
+ } finally {
258
+ writer.releaseLock()
259
+ writing = undefined
260
+ }
261
+ },
262
+ startTls: async () => workersSocket(socket.startTls()),
263
+ // `close()` alone waits for a write the server never takes.
264
+ close() {
265
+ void (writing ?? socket.writable).abort().catch(() => {})
266
+ void (reading ?? socket.readable).cancel().catch(() => {})
267
+ end()
268
+ },
269
+ end,
270
+ }
271
+ }
272
+
273
+ export function workersConnect(connect: WorkersConnect): SmtpConnect {
274
+ return async ({ host, port }, signal) => {
275
+ const socket = connect({ hostname: host, port }, { secureTransport: "starttls", allowHalfOpen: false })
276
+ const opened = workersSocket(socket)
277
+ signal.addEventListener("abort", opened.close)
278
+ try {
279
+ await socket.opened
280
+ return opened
281
+ } catch (error) {
282
+ opened.close()
283
+ throw error
284
+ } finally {
285
+ signal.removeEventListener("abort", opened.close)
286
+ }
287
+ }
288
+ }
289
+
290
+ /** `Bun.connect` on bun, `cloudflare:sockets` where it can be imported (Workers), else `node:net`. */
291
+ export const platformConnect: SmtpConnect = async (target, signal) => {
292
+ if (typeof Bun !== "undefined") return bunConnect(target, signal)
293
+ const specifier = "cloudflare:sockets"
294
+ const workers = (await import(specifier).catch(() => undefined)) as { connect: WorkersConnect } | undefined
295
+ return (workers ? workersConnect(workers.connect) : nodeConnect)(target, signal)
296
+ }
package/src/test.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { readdir, readFile, rm } from "node:fs/promises"
2
+ import { dirname, join, resolve } from "node:path"
3
+ import { useTestContext } from "hamur/test"
4
+ import { useTestLoader } from "hamur/test/internal"
5
+
6
+ /** One `.json` of the outbox. */
7
+ export interface MailRecord {
8
+ id: string
9
+ date: string
10
+ from: string
11
+ to: string[]
12
+ cc: string[]
13
+ bcc: string[]
14
+ subject: string
15
+ template?: string
16
+ html: string
17
+ text: string
18
+ headers: Record<string, string>
19
+ attachments: Array<{ filename: string; contentType: string; size: number }>
20
+ }
21
+
22
+ export interface SentMailOptions {
23
+ /** The outbox directory; default the one of the test app or of the test preload. */
24
+ dir?: string
25
+ }
26
+
27
+ async function outboxDir(options: SentMailOptions | undefined): Promise<string> {
28
+ if (options?.dir !== undefined) return resolve(options.dir)
29
+ try {
30
+ return join(dirname(useTestContext().outputDir), ".hamur", "mail")
31
+ } catch {}
32
+ try {
33
+ return join((await useTestLoader()).hamur.options.buildDir, "mail")
34
+ } catch (error) {
35
+ throw new Error(
36
+ "@hamur/mail/test: no outbox to read; call setup() from hamur/test in this file or run the tests with the hamur/test/preload",
37
+ { cause: error },
38
+ )
39
+ }
40
+ }
41
+
42
+ async function names(dir: string): Promise<string[]> {
43
+ try {
44
+ return await readdir(dir)
45
+ } catch (error) {
46
+ if ((error as { code?: string }).code === "ENOENT") return []
47
+ throw error
48
+ }
49
+ }
50
+
51
+ /** The messages in the outbox, oldest first. */
52
+ export async function sentMail(options?: SentMailOptions): Promise<MailRecord[]> {
53
+ const dir = await outboxDir(options)
54
+ return Promise.all(
55
+ (await names(dir))
56
+ .filter((name) => name.endsWith(".json"))
57
+ .sort()
58
+ .map(async (name) => JSON.parse(await readFile(join(dir, name), "utf8")) as MailRecord),
59
+ )
60
+ }
61
+
62
+ /** Removes every message of the outbox. */
63
+ export async function clearSentMail(options?: SentMailOptions): Promise<void> {
64
+ const dir = await outboxDir(options)
65
+ await Promise.all(
66
+ (await names(dir))
67
+ .filter((name) => /\.(?:eml|json)$/.test(name))
68
+ .map((name) => rm(join(dir, name), { force: true })),
69
+ )
70
+ }
@@ -0,0 +1,35 @@
1
+ import type { RenderedMail, ResolvedMailTransport } from "./types.ts"
2
+
3
+ /** One message as a transport receives it: the MIME text, the SMTP envelope and the message it was written from. */
4
+ export interface OutgoingMail {
5
+ /** The Message-ID without `<>`. */
6
+ id: string
7
+ date: Date
8
+ raw: string
9
+ envelope: { from: string; to: string[] }
10
+ message: RenderedMail
11
+ }
12
+
13
+ export interface MailSender {
14
+ send(mail: OutgoingMail): Promise<void>
15
+ }
16
+
17
+ /** What the run tells a transport: `reuse` is false where a connection must not outlive a send (the serverless presets). */
18
+ export interface TransportRuntime {
19
+ reuse: boolean
20
+ }
21
+
22
+ export type OpenTransport = (config: ResolvedMailTransport, runtime: TransportRuntime) => MailSender
23
+
24
+ /** A failure that does not rule out that a recipient has the message: sending it again may deliver it twice. */
25
+ export class UnconfirmedError extends Error {}
26
+
27
+ /** A transport that sends one message per recipient failed after some were served: sending it again reaches those twice. */
28
+ export class PartialDeliveryError extends UnconfirmedError {
29
+ constructor(served: number, total: number, text: string, cause: unknown) {
30
+ super(
31
+ `the message reached ${served} of ${total} recipients before one failed; sending it again delivers it twice to those ${served}${text ? `: ${text}` : ""}`,
32
+ { cause },
33
+ )
34
+ }
35
+ }
@@ -0,0 +1,68 @@
1
+ import { outsideWorker } from "hamur/server"
2
+ import { recipients, shown } from "./http.ts"
3
+ import { PartialDeliveryError, type MailSender, type OpenTransport } from "../transport.ts"
4
+
5
+ /** `EmailMessage` of `cloudflare:email`. */
6
+ type EmailMessageConstructor = new (from: string, to: string, raw: string) => unknown
7
+
8
+ /** The part of a `send_email` binding the transport calls. */
9
+ interface SendEmailBinding {
10
+ send(message: unknown): Promise<unknown>
11
+ }
12
+
13
+ /** What a test changes: where the Worker's `env` and `EmailMessage` come from. */
14
+ export interface CloudflareDeps {
15
+ env?: () => Promise<Record<string, unknown>>
16
+ emailMessage?: () => Promise<EmailMessageConstructor>
17
+ }
18
+
19
+ const SPECIFIER_ENV = "cloudflare:workers"
20
+ const SPECIFIER_EMAIL = "cloudflare:email"
21
+
22
+ async function workersEnv(binding: string): Promise<Record<string, unknown>> {
23
+ try {
24
+ return ((await import(SPECIFIER_ENV)) as { env: Record<string, unknown> }).env
25
+ } catch {
26
+ return outsideWorker(`mail uses the cloudflare send_email binding ${JSON.stringify(binding)}`)
27
+ }
28
+ }
29
+
30
+ async function workersEmailMessage(): Promise<EmailMessageConstructor> {
31
+ return ((await import(SPECIFIER_EMAIL)) as { EmailMessage: EmailMessageConstructor }).EmailMessage
32
+ }
33
+
34
+ /**
35
+ * `env[binding].send(new EmailMessage(from, to, raw))`, one per envelope recipient, in order, stopping at the first
36
+ * refusal. A refusal after some recipients were served fails with their count, since sending the message again reaches them twice.
37
+ */
38
+ export function createCloudflare(config: { binding: string }, deps: CloudflareDeps = {}): MailSender {
39
+ const { binding } = config
40
+ return {
41
+ async send(mail) {
42
+ const values = await (deps.env ?? (() => workersEnv(binding)))()
43
+ const found = values[binding] as SendEmailBinding | undefined
44
+ if (!found || typeof found.send !== "function")
45
+ throw new Error(
46
+ `The cloudflare mail transport found no send_email binding "${binding}" in env (mail.transport.binding; declare it in send_email of the wrangler config)`,
47
+ )
48
+ const EmailMessage = await (deps.emailMessage ?? workersEmailMessage)()
49
+ const { to, from } = mail.envelope
50
+ for (const [served, address] of to.entries()) {
51
+ try {
52
+ await found.send(new EmailMessage(from, address, mail.raw))
53
+ } catch (cause) {
54
+ const text = shown(cause instanceof Error ? cause.message : "", recipients(mail))
55
+ if (served > 0) throw new PartialDeliveryError(served, to.length, text, cause)
56
+ throw new Error(text || "the send_email binding refused the message", { cause })
57
+ }
58
+ }
59
+ },
60
+ }
61
+ }
62
+
63
+ const open: OpenTransport = (config) => {
64
+ if (config.type !== "cloudflare") throw new Error(`the cloudflare transport cannot open a ${config.type} transport`)
65
+ return createCloudflare(config)
66
+ }
67
+
68
+ export default open
@@ -0,0 +1,75 @@
1
+ import { readSecret } from "hamur/server/internal"
2
+ import { quotedName } from "../address.ts"
3
+ import { UNCONFIRMED } from "../smtp/client.ts"
4
+ import { UnconfirmedError, type OutgoingMail } from "../transport.ts"
5
+ import type { ParsedAddress } from "../types.ts"
6
+
7
+ /** What a test changes: `endpoint` replaces the provider's origin. */
8
+ export interface HttpDeps {
9
+ fetch?: typeof fetch
10
+ endpoint?: string
11
+ timeout?: number
12
+ }
13
+
14
+ export const TIMEOUT = 30_000
15
+ const MAX_ERROR = 500
16
+ const NEVER_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"])
17
+ const CONTROLS = /[\x00-\x1f\x7f]+/g
18
+ const encoder = new TextEncoder()
19
+
20
+ export const secret = (value: unknown, option: string): string => readSecret(value, `mail.transport.${option}`)
21
+
22
+ export const address = (parsed: ParsedAddress): string =>
23
+ parsed.name ? `${quotedName(parsed.name)} <${parsed.address}>` : parsed.address
24
+
25
+ export function base64(bytes: Uint8Array): string {
26
+ let text = ""
27
+ for (let at = 0; at < bytes.length; at += 0x2000) text += String.fromCharCode(...bytes.subarray(at, at + 0x2000))
28
+ return btoa(text)
29
+ }
30
+
31
+ export const base64Text = (text: string): string => base64(encoder.encode(text))
32
+
33
+ const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
34
+
35
+ /** The provider's text without the secrets and addresses it repeats, controls as spaces, at most 500 characters. */
36
+ export function shown(text: string, hidden: string[]): string {
37
+ const values = hidden.filter(Boolean).sort((a, b) => b.length - a.length)
38
+ const clean = values.length ? text.replace(new RegExp(values.map(escape).join("|"), "gi"), "…") : text
39
+ return clean.replace(CONTROLS, " ").trim().slice(0, MAX_ERROR)
40
+ }
41
+
42
+ export const recipients = (mail: OutgoingMail): string[] => [...mail.envelope.to, mail.envelope.from]
43
+
44
+ /**
45
+ * One POST. A rejection of `fetch` (timeout, reset, no answer) may come after the provider took the message, so it is the
46
+ * `UNCONFIRMED` failure, unless no connection was made; a non-2xx answer is a refusal with its status and the start of its body.
47
+ * A 5xx other than 503 may come from a gateway or a server that failed after the provider took the message.
48
+ */
49
+ export async function post(
50
+ url: string,
51
+ init: { headers: HeadersInit; body: BodyInit },
52
+ hidden: string[],
53
+ deps: HttpDeps,
54
+ ): Promise<void> {
55
+ const signal = AbortSignal.timeout(deps.timeout ?? TIMEOUT)
56
+ let response: Response
57
+ try {
58
+ response = await (deps.fetch ?? fetch)(url, { method: "POST", redirect: "manual", signal, ...init })
59
+ } catch (cause) {
60
+ const { code = (cause as { cause?: { code?: string } }).cause?.code } = cause as { code?: unknown }
61
+ if (typeof code === "string" && NEVER_SENT.has(code))
62
+ throw new Error(`cannot connect to the provider (${code})`, { cause })
63
+ throw new UnconfirmedError(UNCONFIRMED, { cause })
64
+ }
65
+ if (response.ok) {
66
+ await response.body?.cancel().catch(() => undefined)
67
+ return
68
+ }
69
+ const body = await response.text().catch(() => "")
70
+ const text = shown(body, hidden)
71
+ const message = text ? `HTTP ${response.status}: ${text}` : `HTTP ${response.status}`
72
+ throw response.status >= 500 && response.status !== 503 ? new UnconfirmedError(message) : new Error(message)
73
+ }
74
+
75
+ export const origin = (deps: HttpDeps, provider: string): string => (deps.endpoint ?? provider).replace(/\/+$/, "")
@@ -0,0 +1,31 @@
1
+ import { base64Text, origin, post, recipients, secret, type HttpDeps } from "./http.ts"
2
+ import type { MailSender, OpenTransport } from "../transport.ts"
3
+
4
+ export function createMailgun(
5
+ config: { apiKey: unknown; domain: string; region?: "us" | "eu" },
6
+ deps: HttpDeps = {},
7
+ ): MailSender {
8
+ return {
9
+ async send(mail) {
10
+ const key = secret(config.apiKey, "apiKey")
11
+ const form = new FormData()
12
+ for (const to of mail.envelope.to) form.append("to", to)
13
+ form.append("message", new Blob([mail.raw], { type: "message/rfc822" }), "message.mime")
14
+ for (const tag of mail.message.tags) form.append("o:tag", tag)
15
+ const basic = base64Text(`api:${key}`)
16
+ await post(
17
+ `${origin(deps, config.region === "eu" ? "https://api.eu.mailgun.net" : "https://api.mailgun.net")}/v3/${encodeURIComponent(config.domain)}/messages.mime`,
18
+ { headers: { authorization: `Basic ${basic}` }, body: form },
19
+ [key, basic, ...recipients(mail)],
20
+ deps,
21
+ )
22
+ },
23
+ }
24
+ }
25
+
26
+ const open: OpenTransport = (config) => {
27
+ if (config.type !== "mailgun") throw new Error(`the mailgun transport cannot open a ${config.type} transport`)
28
+ return createMailgun(config)
29
+ }
30
+
31
+ export default open
@@ -0,0 +1,64 @@
1
+ import { mkdir, readdir, unlink, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { shownAddress } from "../address.ts"
4
+ import type { MailSender, OpenTransport, OutgoingMail } from "../transport.ts"
5
+
6
+ /** The newest pairs the outbox keeps. */
7
+ export const KEEP = 200
8
+
9
+ /** What the outbox writes next to each `.eml`, read by the `mail` tab and `sentMail`. */
10
+ export function outboxRecord(mail: OutgoingMail): Record<string, unknown> {
11
+ const { message } = mail
12
+ return {
13
+ id: mail.id,
14
+ date: mail.date.toISOString(),
15
+ from: shownAddress(message.from),
16
+ to: message.to.map(shownAddress),
17
+ cc: message.cc.map(shownAddress),
18
+ bcc: message.bcc.map(shownAddress),
19
+ subject: message.subject,
20
+ ...(message.template === undefined ? {} : { template: message.template }),
21
+ html: message.html,
22
+ text: message.text ?? "",
23
+ headers: message.headers,
24
+ attachments: message.attachments.map((attachment) => ({
25
+ filename: attachment.filename,
26
+ contentType: attachment.contentType,
27
+ size: attachment.content.length,
28
+ })),
29
+ }
30
+ }
31
+
32
+ async function prune(dir: string, keep: number): Promise<void> {
33
+ const names = await readdir(dir)
34
+ const stems = [
35
+ ...new Set(names.filter((name) => /\.(?:eml|json)$/.test(name)).map((name) => name.replace(/\.(?:eml|json)$/, ""))),
36
+ ]
37
+ stems.sort()
38
+ const old = stems.slice(0, Math.max(0, stems.length - keep))
39
+ await Promise.all(
40
+ old.flatMap((stem) =>
41
+ [".eml", ".json"].map((extension) => unlink(join(dir, stem + extension)).catch(() => undefined)),
42
+ ),
43
+ )
44
+ }
45
+
46
+ /** Each message as `<dir>/<ISO time>-<id>.eml` and `.json`, the newest `keep` pairs kept. */
47
+ export function createOutbox(dir: string, keep = KEEP): MailSender {
48
+ return {
49
+ async send(mail) {
50
+ await mkdir(dir, { recursive: true })
51
+ const stem = join(dir, `${mail.date.toISOString()}-${mail.id}`)
52
+ await writeFile(`${stem}.eml`, mail.raw)
53
+ await writeFile(`${stem}.json`, `${JSON.stringify(outboxRecord(mail), null, 2)}\n`)
54
+ await prune(dir, keep)
55
+ },
56
+ }
57
+ }
58
+
59
+ const open: OpenTransport = (config) => {
60
+ if (config.type !== "outbox") throw new Error(`the outbox transport cannot open a ${config.type} transport`)
61
+ return createOutbox(config.dir)
62
+ }
63
+
64
+ export default open