@sigil-dev/mail 0.0.0-stage → 0.9.32
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.
- package/README.md +37 -3
- package/index.ts +351 -0
- package/message.ts +127 -0
- package/package.json +32 -4
- package/render.ts +180 -0
- package/smtp.ts +289 -0
- package/transport.ts +70 -0
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @sigil-dev/mail
|
|
2
|
+
|
|
3
|
+
Mail for a Grimoire app. A template is a component, sending reads like English, and delivery goes through the job queue, so a mail server that is down for a minute costs nothing.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
sigil add mail
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
// src/mail/welcome.tsx
|
|
11
|
+
import { Mail } from "@sigil-dev/mail";
|
|
12
|
+
|
|
13
|
+
export default function Welcome({ name, url }: { name: string; url: string }) {
|
|
14
|
+
return (
|
|
15
|
+
<Mail subject={`Welcome, ${name}`} preview="Confirm your email">
|
|
16
|
+
<p>Hi {name},</p>
|
|
17
|
+
<a href={url}>Confirm</a>
|
|
18
|
+
</Mail>
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
export const sample = { name: "Cane", url: "https://example.com" }; // for /__mail
|
|
22
|
+
|
|
23
|
+
// sigil.config.ts
|
|
24
|
+
plugins: [tome(), jobs(), mail({ from: "App <hi@example.com>" })]
|
|
25
|
+
|
|
26
|
+
// a route
|
|
27
|
+
await mail.to(user.email).send(<Welcome name={user.name} url={url} />); // queued
|
|
28
|
+
await mail.to(user.email).later("10m").send(<Welcome name={user.name} url={url} />);
|
|
29
|
+
await mail.to(user.email).now(<Welcome name={user.name} url={url} />); // here, now
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- The template is rendered when you call `send`, so props are any value a page takes, and a broken template fails there, not in a worker later.
|
|
33
|
+
- `SMTP_URL` (`smtp://user:pass@host:587`, upgraded with STARTTLS, or `smtps://…:465`) is read when the server starts. Passwords never cross the network unencrypted.
|
|
34
|
+
- In development without `SMTP_URL`, nothing is sent: `/__mail` shows every template with its `sample` props, and what the app tried to send.
|
|
35
|
+
- Tests: `mail({ transport: outbox() })`, then look at `outbox.sent`.
|
|
36
|
+
|
|
37
|
+
Docs: https://sigil.cane1712.dev/docs/reference/mail
|
package/index.ts
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import type { Duration, GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
4
|
+
import { defineJob } from "@sigil-dev/plugin-jobs";
|
|
5
|
+
import { type Address, type Message, mailbox, mailboxes } from "./message.ts";
|
|
6
|
+
import { readRendered, toText } from "./render.ts";
|
|
7
|
+
import { smtp } from "./smtp.ts";
|
|
8
|
+
import { type Kept, log, outbox, type Transport } from "./transport.ts";
|
|
9
|
+
|
|
10
|
+
export { type Address, type Mailbox, type Message, toMime } from "./message.ts";
|
|
11
|
+
export { Mail, type MailProps, toText } from "./render.ts";
|
|
12
|
+
export { SmtpError, type SmtpOptions, smtp } from "./smtp.ts";
|
|
13
|
+
export { type Kept, log, outbox, type Transport } from "./transport.ts";
|
|
14
|
+
|
|
15
|
+
/** What `send` takes: a rendered template (`<Welcome … />`), or the parts by hand. */
|
|
16
|
+
export type Content =
|
|
17
|
+
| unknown
|
|
18
|
+
| { subject: string; html: string; text?: string };
|
|
19
|
+
|
|
20
|
+
/** A mail being addressed. Each call returns a new one, so a partial one can be reused. */
|
|
21
|
+
export interface Draft {
|
|
22
|
+
cc(address: Address | readonly Address[]): Draft;
|
|
23
|
+
bcc(address: Address | readonly Address[]): Draft;
|
|
24
|
+
replyTo(address: Address): Draft;
|
|
25
|
+
/** Overrides the configured sender. */
|
|
26
|
+
from(address: Address): Draft;
|
|
27
|
+
header(name: string, value: string): Draft;
|
|
28
|
+
/** Deliver after this long, through the queue. */
|
|
29
|
+
later(delay: Duration): Draft;
|
|
30
|
+
/** Deliver at this time, through the queue. */
|
|
31
|
+
at(when: Date): Draft;
|
|
32
|
+
/**
|
|
33
|
+
* Render now, deliver from the job queue: retried when the server is
|
|
34
|
+
* down, and the request does not wait for SMTP. Needs plugin-jobs.
|
|
35
|
+
*
|
|
36
|
+
* `send(<Welcome name="Ann" />)`, or in a .ts file, `send(Welcome, { name: "Ann" })`.
|
|
37
|
+
*/
|
|
38
|
+
send<P>(template: (props: P) => unknown, props: P): Promise<{ id: string }>;
|
|
39
|
+
send(content: Content): Promise<{ id: string }>;
|
|
40
|
+
/** Render and deliver here, now: the caller waits, and a failure throws. */
|
|
41
|
+
now<P>(template: (props: P) => unknown, props: P): Promise<{ id: string }>;
|
|
42
|
+
now(content: Content): Promise<{ id: string }>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface MailOptions {
|
|
46
|
+
/** The sender when a mail names none: `"Sigil <hi@example.com>"`. */
|
|
47
|
+
from?: Address;
|
|
48
|
+
/** Where mail goes. Default: smtp() when SMTP_URL is set, log() in development. */
|
|
49
|
+
transport?: Transport;
|
|
50
|
+
/** Where templates live. Default `src/mail`. */
|
|
51
|
+
dir?: string;
|
|
52
|
+
/** Attempts per mail before the queue gives up. Default 5. */
|
|
53
|
+
attempts?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type MailPlugin = GrimoirePlugin<{
|
|
57
|
+
mail: { to(address: Address | readonly Address[]): Draft };
|
|
58
|
+
}>;
|
|
59
|
+
|
|
60
|
+
/** What the plugin was made with, for the process: sending and the queue's worker both read it. */
|
|
61
|
+
let settings: MailOptions = {};
|
|
62
|
+
let resolved: Transport | undefined;
|
|
63
|
+
let dev = process.env.NODE_ENV !== "production";
|
|
64
|
+
/** Under createTestApp: every mail goes to `tested`, at once, and never leaves. */
|
|
65
|
+
let testing = false;
|
|
66
|
+
const tested = outbox();
|
|
67
|
+
|
|
68
|
+
function transport(): Transport {
|
|
69
|
+
if (resolved) return resolved;
|
|
70
|
+
if (testing) resolved = tested;
|
|
71
|
+
else if (settings.transport) resolved = settings.transport;
|
|
72
|
+
else if (process.env.SMTP_URL) resolved = smtp();
|
|
73
|
+
else if (dev) resolved = log();
|
|
74
|
+
else {
|
|
75
|
+
throw new Error(
|
|
76
|
+
"mail: nowhere to send. Set SMTP_URL, or pass a transport: mail({ transport: smtp({ url }) }).",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return resolved;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The one job that delivers queued mail: the message is already rendered. */
|
|
83
|
+
const deliver = defineJob<Message>({
|
|
84
|
+
attempts: 5,
|
|
85
|
+
async handler(message) {
|
|
86
|
+
await transport().send(message);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
export const DELIVERY_JOB = "sigil-mail";
|
|
90
|
+
|
|
91
|
+
interface Parts {
|
|
92
|
+
to: Address[];
|
|
93
|
+
cc: Address[];
|
|
94
|
+
bcc: Address[];
|
|
95
|
+
replyTo?: Address;
|
|
96
|
+
from?: Address;
|
|
97
|
+
headers: Record<string, string>;
|
|
98
|
+
delay?: Duration;
|
|
99
|
+
at?: Date;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The message: the template's output read, the addresses checked. */
|
|
103
|
+
function compose(parts: Parts, content: Content): Message {
|
|
104
|
+
const hand = content as { subject?: unknown; html?: unknown; text?: unknown };
|
|
105
|
+
const rendered =
|
|
106
|
+
typeof hand?.subject === "string" && typeof hand?.html === "string"
|
|
107
|
+
? {
|
|
108
|
+
subject: hand.subject,
|
|
109
|
+
html: hand.html,
|
|
110
|
+
text: typeof hand.text === "string" ? hand.text : "",
|
|
111
|
+
}
|
|
112
|
+
: readRendered(content);
|
|
113
|
+
const from =
|
|
114
|
+
parts.from ??
|
|
115
|
+
("from" in rendered ? rendered.from : undefined) ??
|
|
116
|
+
settings.from ??
|
|
117
|
+
process.env.MAIL_FROM;
|
|
118
|
+
if (!from)
|
|
119
|
+
throw new Error(
|
|
120
|
+
'mail: no sender. Set MAIL_FROM, or mail({ from: "App <hi@example.com>" })',
|
|
121
|
+
);
|
|
122
|
+
const to = mailboxes(parts.to);
|
|
123
|
+
if (to.length === 0) throw new Error("mail: no recipient");
|
|
124
|
+
const replyTo =
|
|
125
|
+
parts.replyTo ?? ("replyTo" in rendered ? rendered.replyTo : undefined);
|
|
126
|
+
return {
|
|
127
|
+
from: mailbox(from as Address),
|
|
128
|
+
to,
|
|
129
|
+
cc: mailboxes(parts.cc),
|
|
130
|
+
bcc: mailboxes(parts.bcc),
|
|
131
|
+
...(replyTo ? { replyTo: mailbox(replyTo as Address) } : {}),
|
|
132
|
+
subject: rendered.subject,
|
|
133
|
+
html: rendered.html,
|
|
134
|
+
text: rendered.text || toText(rendered.html),
|
|
135
|
+
headers: parts.headers,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** `send(Welcome, props)` is `send(<Welcome {...props} />)`: the same render. */
|
|
140
|
+
const content = (template: unknown, props: unknown[]): Content =>
|
|
141
|
+
typeof template === "function" && props.length > 0
|
|
142
|
+
? (template as (p: unknown) => unknown)(props[0])
|
|
143
|
+
: template;
|
|
144
|
+
|
|
145
|
+
function draft(parts: Parts): Draft {
|
|
146
|
+
const next = (more: Partial<Parts>) => draft({ ...parts, ...more });
|
|
147
|
+
return {
|
|
148
|
+
cc: (a) =>
|
|
149
|
+
next({ cc: [...parts.cc, ...(Array.isArray(a) ? a : [a as Address])] }),
|
|
150
|
+
bcc: (a) =>
|
|
151
|
+
next({ bcc: [...parts.bcc, ...(Array.isArray(a) ? a : [a as Address])] }),
|
|
152
|
+
replyTo: (a) => next({ replyTo: a }),
|
|
153
|
+
from: (a) => next({ from: a }),
|
|
154
|
+
header: (name, value) =>
|
|
155
|
+
next({ headers: { ...parts.headers, [name]: value } }),
|
|
156
|
+
later: (delay) => next({ delay }),
|
|
157
|
+
at: (when) => next({ at: when }),
|
|
158
|
+
async send(template: unknown, ...props: unknown[]) {
|
|
159
|
+
const message = compose(parts, content(template, props));
|
|
160
|
+
if (testing) return transport().send(message);
|
|
161
|
+
try {
|
|
162
|
+
const job = parts.at
|
|
163
|
+
? deliver.at(parts.at)
|
|
164
|
+
: parts.delay !== undefined
|
|
165
|
+
? deliver.in(parts.delay)
|
|
166
|
+
: deliver;
|
|
167
|
+
const id = await job.enqueue(message);
|
|
168
|
+
return { id: String(id) };
|
|
169
|
+
} catch (e) {
|
|
170
|
+
const why = (e as Error).message ?? String(e);
|
|
171
|
+
if (/no name yet|no queue|not registered|sink/i.test(why)) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
"mail: send() delivers through the job queue, and plugin-jobs is not in the config. " +
|
|
174
|
+
"Add it (`sigil add jobs`), or deliver here and now with .now().",
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
throw e;
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
async now(template: unknown, ...props: unknown[]) {
|
|
181
|
+
if (parts.delay !== undefined || parts.at) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
"mail: .now() delivers immediately; later() and at() need send()",
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
return transport().send(compose(parts, content(template, props)));
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const to = (address: Address | readonly Address[]): Draft =>
|
|
192
|
+
draft({
|
|
193
|
+
to: Array.isArray(address) ? [...address] : [address as Address],
|
|
194
|
+
cc: [],
|
|
195
|
+
bcc: [],
|
|
196
|
+
headers: {},
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
/** Template files under `dir`, by name: `welcome`, `auth/reset-password`. */
|
|
200
|
+
function templates(dir: string): string[] {
|
|
201
|
+
if (!existsSync(dir)) return [];
|
|
202
|
+
return (readdirSync(dir, { recursive: true }) as string[])
|
|
203
|
+
.map((f) => f.replace(/\\/g, "/"))
|
|
204
|
+
.filter(
|
|
205
|
+
(f) => /\.tsx$/.test(f) && !f.split("/").some((p) => p.startsWith("_")),
|
|
206
|
+
)
|
|
207
|
+
.map((f) => f.replace(/\.tsx$/, ""))
|
|
208
|
+
.sort();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const esc = (s: string) =>
|
|
212
|
+
s
|
|
213
|
+
.replace(/&/g, "&")
|
|
214
|
+
.replace(/</g, "<")
|
|
215
|
+
.replace(/>/g, ">")
|
|
216
|
+
.replace(/"/g, """);
|
|
217
|
+
|
|
218
|
+
/** /__mail: every template rendered with its `sample` props, and what the log transport kept. */
|
|
219
|
+
async function preview(
|
|
220
|
+
url: URL,
|
|
221
|
+
root: string,
|
|
222
|
+
dir: string,
|
|
223
|
+
): Promise<Response | null> {
|
|
224
|
+
if (url.pathname !== "/__mail" && !url.pathname.startsWith("/__mail/"))
|
|
225
|
+
return null;
|
|
226
|
+
const page = (body: string) =>
|
|
227
|
+
new Response(
|
|
228
|
+
`<!doctype html><meta charset="utf-8"><title>Mail</title><style>body{font:15px system-ui;max-width:52rem;margin:2rem auto;padding:0 1rem}iframe{width:100%;height:32rem;border:1px solid #ccc;border-radius:8px}pre{white-space:pre-wrap;background:#f6f6f6;padding:1rem;border-radius:8px}li{margin:.3rem 0}</style>${body}`,
|
|
229
|
+
{ headers: { "content-type": "text/html; charset=utf-8" } },
|
|
230
|
+
);
|
|
231
|
+
const rest = url.pathname.slice("/__mail".length).replace(/^\//, "");
|
|
232
|
+
|
|
233
|
+
const render = async (name: string) => {
|
|
234
|
+
const file = join(dir, `${name}.tsx`);
|
|
235
|
+
if (!templates(dir).includes(name)) return null;
|
|
236
|
+
const mod = await import(`${file}?v=${statSync(file).mtimeMs}`);
|
|
237
|
+
if (typeof mod.default !== "function")
|
|
238
|
+
throw new Error(`${name}: no default export`);
|
|
239
|
+
return readRendered(mod.default(mod.sample ?? {}));
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
if (rest.startsWith("raw/")) {
|
|
243
|
+
const name = rest.slice(4);
|
|
244
|
+
const m = await render(name);
|
|
245
|
+
return m
|
|
246
|
+
? new Response(m.html, {
|
|
247
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
248
|
+
})
|
|
249
|
+
: null;
|
|
250
|
+
}
|
|
251
|
+
if (rest.startsWith("sent/")) {
|
|
252
|
+
const kept = (resolved as { sent?: Kept[] } | undefined)?.sent?.find(
|
|
253
|
+
(k) => k.id === rest.slice(5),
|
|
254
|
+
);
|
|
255
|
+
return kept
|
|
256
|
+
? new Response(kept.html, {
|
|
257
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
258
|
+
})
|
|
259
|
+
: null;
|
|
260
|
+
}
|
|
261
|
+
if (rest) {
|
|
262
|
+
try {
|
|
263
|
+
const m = await render(rest);
|
|
264
|
+
if (!m) return null;
|
|
265
|
+
return page(
|
|
266
|
+
`<p><a href="/__mail">← all mail</a></p><h1>${esc(m.subject)}</h1>` +
|
|
267
|
+
`<iframe src="/__mail/raw/${esc(rest)}"></iframe><h2>Text</h2><pre>${esc(m.text)}</pre>`,
|
|
268
|
+
);
|
|
269
|
+
} catch (e) {
|
|
270
|
+
return page(
|
|
271
|
+
`<p><a href="/__mail">← all mail</a></p><h1>${esc(rest)}</h1><pre>${esc(String((e as Error).stack ?? e))}</pre>`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const list = templates(dir)
|
|
276
|
+
.map((n) => `<li><a href="/__mail/${esc(n)}">${esc(n)}</a></li>`)
|
|
277
|
+
.join("");
|
|
278
|
+
const sent = ((resolved as { sent?: Kept[] } | undefined)?.sent ?? [])
|
|
279
|
+
.map(
|
|
280
|
+
(k) =>
|
|
281
|
+
`<li><a href="/__mail/sent/${k.id}">${esc(k.subject)}</a> to ${esc(k.to.map((t) => t.email).join(", "))} · ${k.at.toLocaleTimeString()}</li>`,
|
|
282
|
+
)
|
|
283
|
+
.join("");
|
|
284
|
+
return page(
|
|
285
|
+
`<h1>Mail</h1><h2>Templates in ${esc(relative(root, dir) || ".")}</h2>` +
|
|
286
|
+
(list
|
|
287
|
+
? `<ul>${list}</ul>`
|
|
288
|
+
: "<p>None yet: <code>sigil g mail welcome</code>.</p>") +
|
|
289
|
+
`<p>A template shows with the props its <code>sample</code> export gives.</p>` +
|
|
290
|
+
`<h2>Sent in this process</h2>${sent ? `<ul>${sent}</ul>` : "<p>Nothing yet.</p>"}`,
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function plugin(options: MailOptions = {}): MailPlugin {
|
|
295
|
+
settings = options;
|
|
296
|
+
resolved = undefined;
|
|
297
|
+
const dirOption = options.dir ?? "src/mail";
|
|
298
|
+
const dirOf = () => join(process.cwd(), dirOption);
|
|
299
|
+
if (options.attempts !== undefined)
|
|
300
|
+
(deliver as { attempts: number }).attempts = options.attempts;
|
|
301
|
+
|
|
302
|
+
return {
|
|
303
|
+
name: "mail",
|
|
304
|
+
serverOnly: [dirOption],
|
|
305
|
+
...(options.transport?.requiredEnv?.length
|
|
306
|
+
? { requiredEnv: [...options.transport.requiredEnv] }
|
|
307
|
+
: {}),
|
|
308
|
+
// plugin-jobs runs it like a file in src/jobs
|
|
309
|
+
jobs: { [DELIVERY_JOB]: deliver },
|
|
310
|
+
config(config) {
|
|
311
|
+
dev = config.dev ?? dev;
|
|
312
|
+
if (config.test) {
|
|
313
|
+
testing = true;
|
|
314
|
+
resolved = undefined;
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
...config,
|
|
318
|
+
alias: { $mail: dirOption, ...(config.alias ?? {}) },
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
/** The transport is decided at startup, so a missing SMTP_URL fails the boot, not the first mail. */
|
|
322
|
+
async services() {
|
|
323
|
+
const t = transport();
|
|
324
|
+
t.check?.();
|
|
325
|
+
return { mail: { to } };
|
|
326
|
+
},
|
|
327
|
+
async onRequest(req, next) {
|
|
328
|
+
if (!dev) return next();
|
|
329
|
+
const answered = await preview(new URL(req.url), process.cwd(), dirOf());
|
|
330
|
+
return answered ?? next();
|
|
331
|
+
},
|
|
332
|
+
} as MailPlugin & { jobs: Record<string, unknown> };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Mail: `mail({ from })` in sigil.config.ts makes the plugin, and
|
|
337
|
+
* `mail.to(address)` sends.
|
|
338
|
+
*
|
|
339
|
+
* ```tsx
|
|
340
|
+
* await mail.to(user.email).send(<Welcome name={user.name} />); // queued
|
|
341
|
+
* await mail.to(user.email).now(<Welcome name={user.name} />); // here, now
|
|
342
|
+
* ```
|
|
343
|
+
*/
|
|
344
|
+
export const mail: ((options?: MailOptions) => MailPlugin) & {
|
|
345
|
+
to(address: Address | readonly Address[]): Draft;
|
|
346
|
+
/**
|
|
347
|
+
* Under `createTestApp`, every mail the app sent, queued or not, rendered
|
|
348
|
+
* and never delivered. `mail.sent.length = 0` empties it between tests.
|
|
349
|
+
*/
|
|
350
|
+
readonly sent: Kept[];
|
|
351
|
+
} = Object.assign(plugin, { to, sent: tested.sent });
|
package/message.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/** An address: `"a@b.co"`, `"Ann <a@b.co>"`, or `{ name, email }`. */
|
|
2
|
+
export type Address = string | { name?: string; email: string };
|
|
3
|
+
|
|
4
|
+
/** A mail ready to go: rendered, addressed, and plain data, so it can be queued. */
|
|
5
|
+
export interface Message {
|
|
6
|
+
from: Mailbox;
|
|
7
|
+
to: Mailbox[];
|
|
8
|
+
cc: Mailbox[];
|
|
9
|
+
bcc: Mailbox[];
|
|
10
|
+
replyTo?: Mailbox;
|
|
11
|
+
subject: string;
|
|
12
|
+
html: string;
|
|
13
|
+
text: string;
|
|
14
|
+
headers: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface Mailbox {
|
|
18
|
+
name?: string;
|
|
19
|
+
email: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Deliberately plain: one @, something on each side, no spaces or angle
|
|
23
|
+
// brackets. Whether the address exists is the server's question.
|
|
24
|
+
const EMAIL = /^[^\s@<>"(),;:]+@[^\s@<>"(),;:]+\.[^\s@<>"(),;:]+$/;
|
|
25
|
+
|
|
26
|
+
/** Rejects anything that could end a header line: header injection. */
|
|
27
|
+
function oneLine(value: string, what: string): string {
|
|
28
|
+
if (/[\r\n]/.test(value))
|
|
29
|
+
throw new Error(`mail: ${what} cannot contain a line break`);
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Reads an address in any of its forms; throws, naming it, when it is not one. */
|
|
34
|
+
export function mailbox(address: Address): Mailbox {
|
|
35
|
+
let name: string | undefined;
|
|
36
|
+
let email: string;
|
|
37
|
+
if (typeof address === "string") {
|
|
38
|
+
const m = /^\s*(.*?)\s*<([^<>]+)>\s*$/.exec(address);
|
|
39
|
+
if (m) {
|
|
40
|
+
name = m[1]!.replace(/^"(.*)"$/, "$1") || undefined;
|
|
41
|
+
email = m[2]!.trim();
|
|
42
|
+
} else email = address.trim();
|
|
43
|
+
} else {
|
|
44
|
+
name = address.name || undefined;
|
|
45
|
+
email = address.email.trim();
|
|
46
|
+
}
|
|
47
|
+
if (!EMAIL.test(email))
|
|
48
|
+
throw new Error(`mail: "${email}" is not an email address`);
|
|
49
|
+
return {
|
|
50
|
+
...(name ? { name: oneLine(name, "a name") } : {}),
|
|
51
|
+
email: oneLine(email, "an address"),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const mailboxes = (
|
|
56
|
+
list: Address | readonly Address[] | undefined,
|
|
57
|
+
): Mailbox[] =>
|
|
58
|
+
list === undefined
|
|
59
|
+
? []
|
|
60
|
+
: (Array.isArray(list) ? list : [list]).map((a) => mailbox(a as Address));
|
|
61
|
+
|
|
62
|
+
const ascii = (s: string) => /^[\x20-\x7e]*$/.test(s);
|
|
63
|
+
|
|
64
|
+
/** A header word, as RFC 2047 says, when it is not plain ASCII. */
|
|
65
|
+
function word(s: string): string {
|
|
66
|
+
return ascii(s)
|
|
67
|
+
? s
|
|
68
|
+
: `=?UTF-8?B?${Buffer.from(s, "utf8").toString("base64")}?=`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function formatMailbox(m: Mailbox): string {
|
|
72
|
+
if (!m.name) return m.email;
|
|
73
|
+
const name = ascii(m.name)
|
|
74
|
+
? `"${m.name.replace(/(["\\])/g, "\\$1")}"`
|
|
75
|
+
: word(m.name);
|
|
76
|
+
return `${name} <${m.email}>`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Base64 in lines of 76, as MIME wants. */
|
|
80
|
+
function base64Lines(s: string): string {
|
|
81
|
+
const b = Buffer.from(s, "utf8").toString("base64");
|
|
82
|
+
return b.replace(/.{1,76}/g, "$&\r\n").trimEnd();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The message as SMTP sends it: headers and a multipart/alternative body,
|
|
87
|
+
* text first and HTML second, so clients show the HTML when they can.
|
|
88
|
+
* Bcc is never written: it only exists in the envelope.
|
|
89
|
+
*/
|
|
90
|
+
export function toMime(message: Message, now = new Date()): string {
|
|
91
|
+
const domain = message.from.email.split("@")[1] ?? "localhost";
|
|
92
|
+
const boundary = `sigil-${crypto.randomUUID()}`;
|
|
93
|
+
const head: string[] = [
|
|
94
|
+
`From: ${formatMailbox(message.from)}`,
|
|
95
|
+
`To: ${message.to.map(formatMailbox).join(", ")}`,
|
|
96
|
+
...(message.cc.length
|
|
97
|
+
? [`Cc: ${message.cc.map(formatMailbox).join(", ")}`]
|
|
98
|
+
: []),
|
|
99
|
+
...(message.replyTo ? [`Reply-To: ${formatMailbox(message.replyTo)}`] : []),
|
|
100
|
+
`Subject: ${word(oneLine(message.subject, "the subject"))}`,
|
|
101
|
+
`Date: ${now.toUTCString().replace("GMT", "+0000")}`,
|
|
102
|
+
`Message-ID: <${crypto.randomUUID()}@${domain}>`,
|
|
103
|
+
"MIME-Version: 1.0",
|
|
104
|
+
];
|
|
105
|
+
for (const [k, v] of Object.entries(message.headers)) {
|
|
106
|
+
if (!/^[A-Za-z0-9-]+$/.test(k))
|
|
107
|
+
throw new Error(`mail: "${k}" is not a header name`);
|
|
108
|
+
head.push(`${k}: ${word(oneLine(v, `the ${k} header`))}`);
|
|
109
|
+
}
|
|
110
|
+
head.push(`Content-Type: multipart/alternative; boundary="${boundary}"`);
|
|
111
|
+
const part = (type: string, body: string) =>
|
|
112
|
+
[
|
|
113
|
+
`--${boundary}`,
|
|
114
|
+
`Content-Type: ${type}; charset=utf-8`,
|
|
115
|
+
"Content-Transfer-Encoding: base64",
|
|
116
|
+
"",
|
|
117
|
+
base64Lines(body),
|
|
118
|
+
].join("\r\n");
|
|
119
|
+
return [
|
|
120
|
+
head.join("\r\n"),
|
|
121
|
+
"",
|
|
122
|
+
part("text/plain", message.text),
|
|
123
|
+
part("text/html", message.html),
|
|
124
|
+
`--${boundary}--`,
|
|
125
|
+
"",
|
|
126
|
+
].join("\r\n");
|
|
127
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sigil-dev/mail",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "Mail for Grimoire: templates as components, sent through the job queue over SMTP, with a dev preview",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"homepage": "https://sigil.cane1712.dev/docs/reference/mail",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://git.cane1712.dev/sigil/sigil.git",
|
|
9
|
+
"directory": "packages/mail"
|
|
10
|
+
},
|
|
11
|
+
"module": "index.ts",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"private": false,
|
|
14
|
+
"version": "0.9.32",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"grimoire",
|
|
17
|
+
"sigil",
|
|
18
|
+
"mail",
|
|
19
|
+
"email",
|
|
20
|
+
"smtp"
|
|
21
|
+
],
|
|
22
|
+
"files": [
|
|
23
|
+
"*.ts",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/bun": "latest"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"typescript": "^5",
|
|
31
|
+
"@sigil-dev/grimoire": "0.9.32",
|
|
32
|
+
"@sigil-dev/plugin-jobs": "0.9.32"
|
|
33
|
+
}
|
|
34
|
+
}
|
package/render.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<Mail>`: the root of a mail template. It renders the HTML document and
|
|
3
|
+
* leaves what the envelope needs (subject, from…) in a comment at the end,
|
|
4
|
+
* which `send` reads back and removes. So a template is a plain component,
|
|
5
|
+
* rendered like any page, and nothing about it has to be queued but its
|
|
6
|
+
* output.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const SAFE = Symbol.for("sigil.safe");
|
|
10
|
+
|
|
11
|
+
/** What the server render of JSX gives: HTML marked safe, read through `.v`. */
|
|
12
|
+
type Rendered = {
|
|
13
|
+
readonly [SAFE]: true;
|
|
14
|
+
readonly v: string;
|
|
15
|
+
toString(): string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const escape = (s: string) =>
|
|
19
|
+
s
|
|
20
|
+
.replace(/&/g, "&")
|
|
21
|
+
.replace(/</g, "<")
|
|
22
|
+
.replace(/>/g, ">")
|
|
23
|
+
.replace(/"/g, """);
|
|
24
|
+
|
|
25
|
+
/** Children as HTML: rendered JSX as is, anything else escaped. */
|
|
26
|
+
function html(children: unknown): string {
|
|
27
|
+
if (
|
|
28
|
+
children === null ||
|
|
29
|
+
children === undefined ||
|
|
30
|
+
children === false ||
|
|
31
|
+
children === true
|
|
32
|
+
)
|
|
33
|
+
return "";
|
|
34
|
+
if (Array.isArray(children)) return children.map(html).join("");
|
|
35
|
+
if ((children as Rendered)?.[SAFE]) return (children as Rendered).v;
|
|
36
|
+
return escape(String(children));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const safe = (v: string): Rendered => ({
|
|
40
|
+
[SAFE]: true,
|
|
41
|
+
v,
|
|
42
|
+
toString() {
|
|
43
|
+
return v;
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export interface MailProps {
|
|
48
|
+
/** The subject line; it may use the template's props. */
|
|
49
|
+
subject: string;
|
|
50
|
+
/** The line clients show after the subject in the inbox. Hidden in the mail itself. */
|
|
51
|
+
preview?: string;
|
|
52
|
+
/** Overrides the configured sender for this mail. */
|
|
53
|
+
from?: string;
|
|
54
|
+
replyTo?: string;
|
|
55
|
+
/** The plain-text version. Default: made from the HTML. */
|
|
56
|
+
text?: string;
|
|
57
|
+
/** The document's language. Default "en". */
|
|
58
|
+
lang?: string;
|
|
59
|
+
children?: unknown;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface Meta {
|
|
63
|
+
subject: string;
|
|
64
|
+
from?: string;
|
|
65
|
+
replyTo?: string;
|
|
66
|
+
text?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const MARK = /<!--sigil-mail ([A-Za-z0-9_-]+)-->\s*$/;
|
|
70
|
+
|
|
71
|
+
export function Mail(props: MailProps): Rendered {
|
|
72
|
+
if (!props.subject) throw new Error("mail: <Mail> needs a subject");
|
|
73
|
+
const meta: Meta = {
|
|
74
|
+
subject: props.subject,
|
|
75
|
+
...(props.from ? { from: props.from } : {}),
|
|
76
|
+
...(props.replyTo ? { replyTo: props.replyTo } : {}),
|
|
77
|
+
...(props.text ? { text: props.text } : {}),
|
|
78
|
+
};
|
|
79
|
+
const preview = props.preview
|
|
80
|
+
? `<div style="display:none;max-height:0;overflow:hidden;opacity:0">${escape(props.preview)}</div>`
|
|
81
|
+
: "";
|
|
82
|
+
return safe(
|
|
83
|
+
`<!doctype html><html lang="${escape(props.lang ?? "en")}"><head>` +
|
|
84
|
+
`<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">` +
|
|
85
|
+
`<title>${escape(props.subject)}</title></head><body>${preview}${html(props.children)}</body></html>` +
|
|
86
|
+
`<!--sigil-mail ${Buffer.from(JSON.stringify(meta), "utf8").toString("base64url")}-->`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface RenderedMail {
|
|
91
|
+
html: string;
|
|
92
|
+
text: string;
|
|
93
|
+
subject: string;
|
|
94
|
+
from?: string;
|
|
95
|
+
replyTo?: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* What a template rendered to: the HTML without its mark, and the envelope's
|
|
100
|
+
* parts from it. Throws when the template is not wrapped in `<Mail>`.
|
|
101
|
+
*/
|
|
102
|
+
export function readRendered(output: unknown): RenderedMail {
|
|
103
|
+
if (output instanceof Promise) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
"mail: the template is async. Load what it needs first and pass it as props.",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const raw = (output as Rendered)?.[SAFE]
|
|
109
|
+
? (output as Rendered).v
|
|
110
|
+
: String(output ?? "");
|
|
111
|
+
const m = MARK.exec(raw);
|
|
112
|
+
if (!m)
|
|
113
|
+
throw new Error(
|
|
114
|
+
"mail: the template must render a <Mail subject=…> at its root",
|
|
115
|
+
);
|
|
116
|
+
const meta = JSON.parse(
|
|
117
|
+
Buffer.from(m[1]!, "base64url").toString("utf8"),
|
|
118
|
+
) as Meta;
|
|
119
|
+
const body = raw.slice(0, m.index);
|
|
120
|
+
return {
|
|
121
|
+
html: body,
|
|
122
|
+
text: meta.text ?? toText(body),
|
|
123
|
+
subject: meta.subject,
|
|
124
|
+
...(meta.from ? { from: meta.from } : {}),
|
|
125
|
+
...(meta.replyTo ? { replyTo: meta.replyTo } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const ENTITIES: Record<string, string> = {
|
|
130
|
+
amp: "&",
|
|
131
|
+
lt: "<",
|
|
132
|
+
gt: ">",
|
|
133
|
+
quot: '"',
|
|
134
|
+
apos: "'",
|
|
135
|
+
nbsp: " ",
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A readable plain-text version of the HTML: paragraphs and line breaks
|
|
140
|
+
* kept, links written as `text (url)`, list items as `- `, nothing hidden.
|
|
141
|
+
*/
|
|
142
|
+
export function toText(source: string): string {
|
|
143
|
+
let s = source
|
|
144
|
+
.replace(/<head[\s\S]*?<\/head>/gi, "")
|
|
145
|
+
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")
|
|
146
|
+
// the inbox preview line is not part of the mail
|
|
147
|
+
.replace(/<div style="display:none[^"]*">[\s\S]*?<\/div>/gi, "")
|
|
148
|
+
.replace(/<!--[\s\S]*?-->/g, "")
|
|
149
|
+
.replace(
|
|
150
|
+
/<a\b[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,
|
|
151
|
+
(_, href: string, label: string) => {
|
|
152
|
+
const text = label.replace(/<[^>]+>/g, "").trim();
|
|
153
|
+
return !text || text === href ? href : `${text} (${href})`;
|
|
154
|
+
},
|
|
155
|
+
)
|
|
156
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
157
|
+
.replace(/<li\b[^>]*>/gi, "\n- ")
|
|
158
|
+
.replace(
|
|
159
|
+
/<\/(p|div|h[1-6]|ul|ol|table|tr|blockquote|section|header|footer)>/gi,
|
|
160
|
+
"\n\n",
|
|
161
|
+
)
|
|
162
|
+
.replace(/<\/(td|th)>/gi, " ")
|
|
163
|
+
.replace(/<[^>]+>/g, "");
|
|
164
|
+
s = s.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (all, code: string) => {
|
|
165
|
+
if (code[0] === "#") {
|
|
166
|
+
const n =
|
|
167
|
+
code[1] === "x" || code[1] === "X"
|
|
168
|
+
? Number.parseInt(code.slice(2), 16)
|
|
169
|
+
: Number(code.slice(1));
|
|
170
|
+
return Number.isFinite(n) ? String.fromCodePoint(n) : all;
|
|
171
|
+
}
|
|
172
|
+
return ENTITIES[code.toLowerCase()] ?? all;
|
|
173
|
+
});
|
|
174
|
+
return s
|
|
175
|
+
.split("\n")
|
|
176
|
+
.map((line) => line.replace(/[ \t]+/g, " ").trim())
|
|
177
|
+
.join("\n")
|
|
178
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
179
|
+
.trim();
|
|
180
|
+
}
|
package/smtp.ts
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
import tls from "node:tls";
|
|
3
|
+
import { type Message, toMime } from "./message.ts";
|
|
4
|
+
import type { Transport } from "./transport.ts";
|
|
5
|
+
|
|
6
|
+
export interface SmtpOptions {
|
|
7
|
+
/**
|
|
8
|
+
* `smtp://user:pass@host:587` (upgraded with STARTTLS) or
|
|
9
|
+
* `smtps://user:pass@host:465` (TLS from the start). Read from `env` when
|
|
10
|
+
* the server starts if not given.
|
|
11
|
+
*/
|
|
12
|
+
url?: string;
|
|
13
|
+
/** The variable holding the URL. Default `SMTP_URL`. */
|
|
14
|
+
env?: string;
|
|
15
|
+
/** The name this machine gives in EHLO. Default: the sender's domain. */
|
|
16
|
+
hostname?: string;
|
|
17
|
+
/** Give up on a step after this long. Default 30 s. */
|
|
18
|
+
timeout?: number;
|
|
19
|
+
/** TLS options: `rejectUnauthorized: false` for a self-signed test server. */
|
|
20
|
+
tls?: tls.ConnectionOptions;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A refusal from the server: `code` is SMTP's, 4xx worth retrying, 5xx not. */
|
|
24
|
+
export class SmtpError extends Error {
|
|
25
|
+
constructor(
|
|
26
|
+
readonly code: number,
|
|
27
|
+
message: string,
|
|
28
|
+
) {
|
|
29
|
+
super(`smtp: ${code} ${message}`);
|
|
30
|
+
}
|
|
31
|
+
get transient(): boolean {
|
|
32
|
+
return this.code >= 400 && this.code < 500;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Settings {
|
|
37
|
+
host: string;
|
|
38
|
+
port: number;
|
|
39
|
+
secure: boolean;
|
|
40
|
+
user?: string;
|
|
41
|
+
pass?: string;
|
|
42
|
+
/** `?insecure`: allow credentials over a plain connection (a local relay). */
|
|
43
|
+
insecure: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function parseSmtpUrl(raw: string): Settings {
|
|
47
|
+
let u: URL;
|
|
48
|
+
try {
|
|
49
|
+
u = new URL(raw);
|
|
50
|
+
} catch {
|
|
51
|
+
throw new Error(
|
|
52
|
+
"mail: the SMTP URL is not a URL; it looks like smtp://user:pass@host:587",
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
if (u.protocol !== "smtp:" && u.protocol !== "smtps:") {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`mail: the SMTP URL starts with smtp:// or smtps://, not ${u.protocol}//`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const secure = u.protocol === "smtps:";
|
|
61
|
+
return {
|
|
62
|
+
host: u.hostname,
|
|
63
|
+
port: u.port ? Number(u.port) : secure ? 465 : 587,
|
|
64
|
+
secure,
|
|
65
|
+
...(u.username ? { user: decodeURIComponent(u.username) } : {}),
|
|
66
|
+
...(u.password ? { pass: decodeURIComponent(u.password) } : {}),
|
|
67
|
+
insecure: u.searchParams.has("insecure"),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One connection, read a reply at a time: SMTP is strictly request and answer. */
|
|
72
|
+
class Session {
|
|
73
|
+
private buffer = "";
|
|
74
|
+
private waiting: ((line: string) => void) | null = null;
|
|
75
|
+
private lines: string[] = [];
|
|
76
|
+
private failure: Error | null = null;
|
|
77
|
+
|
|
78
|
+
constructor(
|
|
79
|
+
private socket: net.Socket,
|
|
80
|
+
private timeout: number,
|
|
81
|
+
) {
|
|
82
|
+
this.attach(socket);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private attach(socket: net.Socket) {
|
|
86
|
+
socket.setEncoding("utf8");
|
|
87
|
+
socket.on("data", (chunk: string) => {
|
|
88
|
+
this.buffer += chunk;
|
|
89
|
+
let i = this.buffer.indexOf("\n");
|
|
90
|
+
while (i >= 0) {
|
|
91
|
+
const line = this.buffer.slice(0, i).replace(/\r$/, "");
|
|
92
|
+
this.buffer = this.buffer.slice(i + 1);
|
|
93
|
+
if (this.waiting) {
|
|
94
|
+
const w = this.waiting;
|
|
95
|
+
this.waiting = null;
|
|
96
|
+
w(line);
|
|
97
|
+
} else this.lines.push(line);
|
|
98
|
+
i = this.buffer.indexOf("\n");
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
const fail = (e: Error) => {
|
|
102
|
+
this.failure = e;
|
|
103
|
+
if (this.waiting) {
|
|
104
|
+
const w = this.waiting;
|
|
105
|
+
this.waiting = null;
|
|
106
|
+
w("");
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
socket.on("error", fail);
|
|
110
|
+
socket.on("close", () =>
|
|
111
|
+
fail(new Error("smtp: the server closed the connection")),
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private line(): Promise<string> {
|
|
116
|
+
const ready = this.lines.shift();
|
|
117
|
+
if (ready !== undefined) return Promise.resolve(ready);
|
|
118
|
+
if (this.failure) return Promise.reject(this.failure);
|
|
119
|
+
return new Promise((resolve, reject) => {
|
|
120
|
+
const timer = setTimeout(() => {
|
|
121
|
+
this.waiting = null;
|
|
122
|
+
reject(new Error("smtp: the server did not answer in time"));
|
|
123
|
+
}, this.timeout);
|
|
124
|
+
this.waiting = (line) => {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
if (this.failure && line === "") reject(this.failure);
|
|
127
|
+
else resolve(line);
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A whole reply, continuation lines (`250-…`) included. */
|
|
133
|
+
async reply(): Promise<{ code: number; lines: string[] }> {
|
|
134
|
+
const lines: string[] = [];
|
|
135
|
+
for (;;) {
|
|
136
|
+
const line = await this.line();
|
|
137
|
+
lines.push(line.slice(4));
|
|
138
|
+
if (line[3] !== "-") return { code: Number(line.slice(0, 3)), lines };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Send a command; throw unless the reply is one of `ok`. */
|
|
143
|
+
async command(text: string | null, ok: number[]): Promise<string[]> {
|
|
144
|
+
if (text !== null) this.socket.write(`${text}\r\n`);
|
|
145
|
+
const { code, lines } = await this.reply();
|
|
146
|
+
if (!ok.includes(code)) throw new SmtpError(code, lines.join(" "));
|
|
147
|
+
return lines;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
write(data: string) {
|
|
151
|
+
this.socket.write(data);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Swap in the encrypted socket after STARTTLS. */
|
|
155
|
+
async upgrade(host: string, options: tls.ConnectionOptions) {
|
|
156
|
+
const plain = this.socket;
|
|
157
|
+
plain.removeAllListeners("data");
|
|
158
|
+
plain.removeAllListeners("close");
|
|
159
|
+
plain.removeAllListeners("error");
|
|
160
|
+
const secure = tls.connect({
|
|
161
|
+
socket: plain,
|
|
162
|
+
...(net.isIP(host) ? {} : { servername: host }),
|
|
163
|
+
...options,
|
|
164
|
+
});
|
|
165
|
+
await new Promise<void>((resolve, reject) => {
|
|
166
|
+
secure.once("secureConnect", () => resolve());
|
|
167
|
+
secure.once("error", reject);
|
|
168
|
+
});
|
|
169
|
+
this.socket = secure;
|
|
170
|
+
this.buffer = "";
|
|
171
|
+
this.lines = [];
|
|
172
|
+
this.failure = null;
|
|
173
|
+
this.attach(secure);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
close() {
|
|
177
|
+
this.socket.end();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function open(s: Settings, options: SmtpOptions): Promise<net.Socket> {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const socket = s.secure
|
|
184
|
+
? tls.connect({
|
|
185
|
+
host: s.host,
|
|
186
|
+
port: s.port,
|
|
187
|
+
...sni(s.host),
|
|
188
|
+
...options.tls,
|
|
189
|
+
})
|
|
190
|
+
: net.connect({ host: s.host, port: s.port });
|
|
191
|
+
socket.once(s.secure ? "secureConnect" : "connect", () => resolve(socket));
|
|
192
|
+
socket.once("error", reject);
|
|
193
|
+
socket.setTimeout(options.timeout ?? 30_000, () =>
|
|
194
|
+
socket.destroy(new Error("smtp: connecting timed out")),
|
|
195
|
+
);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const LOCAL = new Set(["localhost", "127.0.0.1", "::1"]);
|
|
200
|
+
|
|
201
|
+
/** SNI names a host; an IP address is not one, and TLS refuses it. */
|
|
202
|
+
const sni = (host: string) => (net.isIP(host) ? {} : { servername: host });
|
|
203
|
+
|
|
204
|
+
/** Lines starting with "." get another, so none ends the DATA early. */
|
|
205
|
+
const dotStuff = (mime: string) => mime.replace(/(^|\r\n)\./g, "$1..");
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Sending over SMTP, with nothing to install: Mailcow, Postfix, or any
|
|
209
|
+
* provider's relay (SES, Postmark, Resend, Mailgun all offer one).
|
|
210
|
+
*
|
|
211
|
+
* The URL is read when the first mail goes, not when the config loads. A
|
|
212
|
+
* plain connection is upgraded with STARTTLS whenever the server offers it,
|
|
213
|
+
* and credentials are never sent unencrypted, except to localhost or with
|
|
214
|
+
* `?insecure` in the URL.
|
|
215
|
+
*/
|
|
216
|
+
export function smtp(options: SmtpOptions = {}): Transport {
|
|
217
|
+
const env = options.url ? undefined : (options.env ?? "SMTP_URL");
|
|
218
|
+
const settings = () => {
|
|
219
|
+
const url = options.url ?? process.env[env!];
|
|
220
|
+
if (!url)
|
|
221
|
+
throw new Error(
|
|
222
|
+
`mail: smtp() reads its URL from ${env}, which is not set.`,
|
|
223
|
+
);
|
|
224
|
+
return parseSmtpUrl(url);
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
kind: "smtp",
|
|
229
|
+
requiredEnv: env ? [env] : [],
|
|
230
|
+
check() {
|
|
231
|
+
settings();
|
|
232
|
+
},
|
|
233
|
+
async send(message: Message) {
|
|
234
|
+
const s = settings();
|
|
235
|
+
const timeout = options.timeout ?? 30_000;
|
|
236
|
+
const session = new Session(await open(s, options), timeout);
|
|
237
|
+
try {
|
|
238
|
+
await session.command(null, [220]);
|
|
239
|
+
const name =
|
|
240
|
+
options.hostname ?? message.from.email.split("@")[1] ?? "localhost";
|
|
241
|
+
let caps = await session.command(`EHLO ${name}`, [250]);
|
|
242
|
+
let secure = s.secure;
|
|
243
|
+
if (!secure && caps.some((c) => /^STARTTLS\b/i.test(c))) {
|
|
244
|
+
await session.command("STARTTLS", [220]);
|
|
245
|
+
await session.upgrade(s.host, options.tls ?? {});
|
|
246
|
+
secure = true;
|
|
247
|
+
caps = await session.command(`EHLO ${name}`, [250]);
|
|
248
|
+
}
|
|
249
|
+
if (s.user !== undefined) {
|
|
250
|
+
if (!secure && !s.insecure && !LOCAL.has(s.host)) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`mail: ${s.host} offers no TLS, and the password would cross the network in the clear. ` +
|
|
253
|
+
"Use smtps://, a server with STARTTLS, or add ?insecure to the URL if you mean it.",
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const auth = caps.find((c) => /^AUTH\b/i.test(c)) ?? "";
|
|
257
|
+
if (/\bPLAIN\b/i.test(auth) || !/\bLOGIN\b/i.test(auth)) {
|
|
258
|
+
const token = Buffer.from(`\0${s.user}\0${s.pass ?? ""}`).toString(
|
|
259
|
+
"base64",
|
|
260
|
+
);
|
|
261
|
+
await session.command(`AUTH PLAIN ${token}`, [235]);
|
|
262
|
+
} else {
|
|
263
|
+
await session.command("AUTH LOGIN", [334]);
|
|
264
|
+
await session.command(
|
|
265
|
+
Buffer.from(s.user).toString("base64"),
|
|
266
|
+
[334],
|
|
267
|
+
);
|
|
268
|
+
await session.command(
|
|
269
|
+
Buffer.from(s.pass ?? "").toString("base64"),
|
|
270
|
+
[235],
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
await session.command(`MAIL FROM:<${message.from.email}>`, [250]);
|
|
275
|
+
for (const r of [...message.to, ...message.cc, ...message.bcc]) {
|
|
276
|
+
await session.command(`RCPT TO:<${r.email}>`, [250, 251]);
|
|
277
|
+
}
|
|
278
|
+
await session.command("DATA", [354]);
|
|
279
|
+
// toMime ends in CRLF, so the lone dot is a line of its own
|
|
280
|
+
session.write(`${dotStuff(toMime(message))}.\r\n`);
|
|
281
|
+
const accepted = await session.command(null, [250]);
|
|
282
|
+
await session.command("QUIT", [221]).catch(() => {});
|
|
283
|
+
return { id: accepted.join(" ") };
|
|
284
|
+
} finally {
|
|
285
|
+
session.close();
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
package/transport.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Message } from "./message.ts";
|
|
2
|
+
|
|
3
|
+
/** Where mail goes: smtp(), or log() and outbox() for development and tests. */
|
|
4
|
+
export interface Transport {
|
|
5
|
+
readonly kind: string;
|
|
6
|
+
/** Variables it cannot send without, checked when the server starts. */
|
|
7
|
+
readonly requiredEnv?: readonly string[];
|
|
8
|
+
/** Throws when it cannot work at all: called at startup, so the first mail does not find out. */
|
|
9
|
+
check?(): void;
|
|
10
|
+
/** Delivers one message; `id` is whatever the other side calls it. */
|
|
11
|
+
send(message: Message): Promise<{ id: string }>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A message a dev or test transport kept, with when it went. */
|
|
15
|
+
export interface Kept extends Message {
|
|
16
|
+
id: string;
|
|
17
|
+
at: Date;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Sends nothing: prints who a mail is for and its subject, and keeps the
|
|
22
|
+
* last `max` for the dev preview at /__mail. The default in development.
|
|
23
|
+
*/
|
|
24
|
+
export function log(
|
|
25
|
+
options: { max?: number; quiet?: boolean } = {},
|
|
26
|
+
): Transport & { readonly sent: Kept[] } {
|
|
27
|
+
const sent: Kept[] = [];
|
|
28
|
+
const max = options.max ?? 50;
|
|
29
|
+
return {
|
|
30
|
+
kind: "log",
|
|
31
|
+
sent,
|
|
32
|
+
async send(message) {
|
|
33
|
+
const id = crypto.randomUUID();
|
|
34
|
+
sent.unshift({ ...message, id, at: new Date() });
|
|
35
|
+
sent.length = Math.min(sent.length, max);
|
|
36
|
+
if (!options.quiet) {
|
|
37
|
+
console.log(
|
|
38
|
+
`[mail] to ${message.to.map((m) => m.email).join(", ")}: "${message.subject}" (not sent: log transport; see /__mail)`,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
return { id };
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Keeps every message in `sent`, for tests: send, then look.
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* const box = outbox();
|
|
51
|
+
* mail({ transport: box });
|
|
52
|
+
* await mail.to("a@b.co").now(<Welcome name="Ann" />);
|
|
53
|
+
* expect(box.sent[0].subject).toBe("Welcome, Ann");
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export function outbox(): Transport & { readonly sent: Kept[]; clear(): void } {
|
|
57
|
+
const sent: Kept[] = [];
|
|
58
|
+
return {
|
|
59
|
+
kind: "outbox",
|
|
60
|
+
sent,
|
|
61
|
+
clear() {
|
|
62
|
+
sent.length = 0;
|
|
63
|
+
},
|
|
64
|
+
async send(message) {
|
|
65
|
+
const id = crypto.randomUUID();
|
|
66
|
+
sent.push({ ...message, id, at: new Date() });
|
|
67
|
+
return { id };
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|